---恢復內容開始---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
- private MockMvc mockMvc;
-
- @Autowired
- private WebApplicationContext webApplicationContext;
-
- @Before
- public void init() {
- mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
- }
-
- @Test
- public void testRegister() {
-
- UusRegisterReq req = new UusRegisterReq();
- req.setParterKey("KE");
- req.setParterSource(2);
- req.setParterUesrId("1");
- req.setPhone("13122221111");
-
- String data = FastJsonUtils.obj2json(req);
- RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/hehe/register").content(data)
- .contentType(MediaType.APPLICATION_JSON);
- try {
- String res = mockMvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isOk()).andReturn()
- .getResponse().getContentAsString();
- log.info("註冊測試結果:{}", res);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }