---恢复内容开始---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();
- }
- }