当前位置:   article > 正文

SpringBoot单元测试(Service测试、Controller测试、Mock测试)_springboot 测试service

springboot 测试service

前提:新建SpringBoot项目

1、Service测试

Service层测试就是常规测试,例如现在有一个HelloService:

  1. @Service
  2. public class HelloService {
  3. public String sayHello(String name){
  4. return "Hello " + name + " !";
  5. }
  6. }

在idea工具中创建测试类快捷键Ctrl+Shift+T,具体测试代码如下:

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class HelloServiceTest {
  4. @Autowired
  5. HelloService helloService;
  6. @Test
  7. public void contextLoads() {
  8. String hello = helloService.sayHello("Chen");
  9. Assert.assertThat(hello, Matchers.is("Hello Chen !"));//判断测试是否正确,绿色结果正确,黄色则是表示结果值错误
  10. }
  11. }

运行测试类结果:

黄色表示期望值和实际值不匹配

2、Controller测试,这里需要使用到Mock测试

例如有如下Controller

  1. @RestController
  2. public class HelloController {
  3. @GetMapping("/hello")
  4. public String hello(String name){
  5. return "Hello "+ name+ " !";
  6. }
  7. @PostMapping("/book")
  8. public String addBook(@RequestBody Book book){
  9. return book.toString();
  10. }
  11. }

涉及到的实体类:

  1. public class Book {
  2. private Integer id;
  3. private String name;
  4. private String author;
  5. ...(get、set方法省略)
  6. }

测试类代码:

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class HelloControllerTest {
  4. @Autowired
  5. HelloService helloService;
  6. @Autowired
  7. WebApplicationContext wac;//模拟ServletContext环境
  8. MockMvc mockMvc;//声明MockMvc对象
  9. @Before
  10. public void before() {
  11. mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
  12. }
  13. @Test
  14. public void test1() throws Exception {
  15. MvcResult mvcResult = mockMvc.perform(
  16. MockMvcRequestBuilders
  17. .get("/hello")//get请求方法
  18. .contentType(MediaType.APPLICATION_FORM_URLENCODED)//请求内容类型
  19. .param("name","Chen"))//参数
  20. .andExpect(MockMvcResultMatchers.status().isOk())//期望返回状态200
  21. .andDo(MockMvcResultHandlers.print())//指定打印信息
  22. .andReturn();//返回值
  23. System.out.println(mvcResult.getResponse().getContentAsString());
  24. }
  25. @Test
  26. public void test2() throws Exception {
  27. ObjectMapper om = new ObjectMapper();
  28. Book book = new Book();
  29. book.setAuthor("羅貫中");
  30. book.setName("三國演義");
  31. book.setId(1);
  32. String s = om.writeValueAsString(book);
  33. MvcResult mvcResult = mockMvc
  34. .perform(MockMvcRequestBuilders
  35. .post("/book")
  36. .contentType(MediaType.APPLICATION_JSON)
  37. .content(s)
  38. )
  39. .andExpect(MockMvcResultMatchers.status().isOk())
  40. .andReturn();
  41. System.out.println(mvcResult.getResponse().getContentAsString());
  42. }
  43. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/653859
推荐阅读
相关标签
  

闽ICP备14008679号