赞
踩
Service层测试就是常规测试,例如现在有一个HelloService:
- @Service
- public class HelloService {
- public String sayHello(String name){
- return "Hello " + name + " !";
- }
- }
在idea工具中创建测试类快捷键Ctrl+Shift+T,具体测试代码如下:
- @RunWith(SpringRunner.class)
- @SpringBootTest
- public class HelloServiceTest {
-
- @Autowired
- HelloService helloService;
- @Test
- public void contextLoads() {
- String hello = helloService.sayHello("Chen");
- Assert.assertThat(hello, Matchers.is("Hello Chen !"));//判断测试是否正确,绿色结果正确,黄色则是表示结果值错误
- }
-
- }
运行测试类结果:
黄色表示期望值和实际值不匹配
例如有如下Controller
- @RestController
- public class HelloController {
-
- @GetMapping("/hello")
- public String hello(String name){
- return "Hello "+ name+ " !";
- }
- @PostMapping("/book")
- public String addBook(@RequestBody Book book){
- return book.toString();
- }
- }
涉及到的实体类:
- public class Book {
- private Integer id;
- private String name;
- private String author;
- ...(get、set方法省略)
- }
测试类代码:
- @RunWith(SpringRunner.class)
- @SpringBootTest
- public class HelloControllerTest {
-
- @Autowired
- HelloService helloService;
-
- @Autowired
- WebApplicationContext wac;//模拟ServletContext环境
- MockMvc mockMvc;//声明MockMvc对象
-
- @Before
- public void before() {
- mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
-
- }
-
- @Test
- public void test1() throws Exception {
- MvcResult mvcResult = mockMvc.perform(
- MockMvcRequestBuilders
- .get("/hello")//get请求方法
- .contentType(MediaType.APPLICATION_FORM_URLENCODED)//请求内容类型
- .param("name","Chen"))//参数
- .andExpect(MockMvcResultMatchers.status().isOk())//期望返回状态200
- .andDo(MockMvcResultHandlers.print())//指定打印信息
- .andReturn();//返回值
- System.out.println(mvcResult.getResponse().getContentAsString());
- }
- @Test
- public void test2() throws Exception {
- ObjectMapper om = new ObjectMapper();
- Book book = new Book();
- book.setAuthor("羅貫中");
- book.setName("三國演義");
- book.setId(1);
- String s = om.writeValueAsString(book);
- MvcResult mvcResult = mockMvc
- .perform(MockMvcRequestBuilders
- .post("/book")
- .contentType(MediaType.APPLICATION_JSON)
- .content(s)
- )
- .andExpect(MockMvcResultMatchers.status().isOk())
- .andReturn();
- System.out.println(mvcResult.getResponse().getContentAsString());
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。