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.    }  
相關文章
相關標籤/搜索