SpringBoot自动生成测试案例

---恢复内容开始---web

@SpringBootTest注解是SpringBoot自1.4.0版本开始引入的一个用于测试的注解spring

1.添加maven依赖json

<dependency>maven

  <groupId>org.springframework.boot</groupId> spring-boot

  <artifactId>spring-boot-starter-test</artifactId> post

</dependency>单元测试

2.Controller右键->new一个test case,选择本身要生成案例的方法,点击完成。测试

 

3.使用MockMvc进行单元测试,MockMvc是惟一支持Controller测试的。ui

测试类以下:spa

 

  1. private MockMvc mockMvc;  
  2.   
  3.    @Autowired  
  4.    private WebApplicationContext webApplicationContext;  
  5.   
  6.    @Before  
  7.    public void init() {  
  8.        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();  
  9.    }  
  10.   
  11.    @Test  
  12.    public void testRegister() {  
  13.        // fail("Not yet implemented");  
  14.        UusRegisterReq req = new UusRegisterReq();  
  15.        req.setParterKey("KE");  
  16.        req.setParterSource(2);  
  17.        req.setParterUesrId("1");  
  18.        req.setPhone("13122221111");  
  19.   
  20.        String data = FastJsonUtils.obj2json(req);  
  21.        RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/hehe/register").content(data)  
  22.                .contentType(MediaType.APPLICATION_JSON);  
  23.        try {  
  24.            String res = mockMvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isOk()).andReturn()  
  25.                    .getResponse().getContentAsString();  
  26.            log.info("注册测试结果:{}", res);  
  27.        } catch (Exception e) {  
  28.            e.printStackTrace();  
  29.        }  
  30.    }  
相关文章
相关标签/搜索