欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

单元测试Junit Test 聚焦Controller层 Java版

程序员文章站 2022-04-29 14:42:41
...

概要:

  1. 演示如何从Controller层完成单个API的单元测试任务
  2. 单个API单元测试编写规范:一个Api对应一个测试类class,应尽可能包含Api调用会出现的状况
  3. 聚焦Controller的测试模板代码块讲解细化
  4. 涉及 Assertions , AssertJ 等Api的常规用法
  5. 先展示Controller层代码,再展示Tests代码,方便对照着查看
  • Controller
/**
 * @Description 家访Admin
 * @Author blake
 * @Date 2019-01-28 11:53
 * @Version 1.0
 */
@Api(tags = "07. 家访管理", description = "家访详情、家访列表")
@RestController
@RequestMapping("/api/admin/home")
public class AdminHomeVisitController {

    @Autowired
    private AdminHomeVisitService adminHomeVisitService;

    @ApiOperation(value = "家访列表", response = HomeVisitResponse.class, responseContainer = "List")
    @GetMapping("/visits")
    public Response listHomeVisit(HomeVisitSearchRequest request, Pageable pageable) {

        return JsonSend.success(adminHomeVisitService.listHomeVisit(request, pageable));
    }

    @ApiOperation(value = "家访详情", response = HomeVisitResponse.class)
    @GetMapping("/visit/{id}")
    public Response getHomeVisitInfo(@PathVariable @ApiParam("家访id") Long id) {

        return JsonSend.success(adminHomeVisitService.getHomeVisitInfo(id));
    }

}
  • Controller Tests
/**
 * @Description
 * @Author blake
 * @Date 2019-01-28 16:09
 * @Version 1.0
 */
@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest
@Transactional
@Sql("classpath:/sql/admin/homevisit/getHomeVisitInfoTests.sql")
public class GetHomeVisitInfoTests extends BaseAdminControllerTest {

    protected static String BASE_HOST = "http://127.0.0.1:10000";

    @Autowired
    protected ObjectMapper mObjectMapper;

    @Autowired
    protected DSLContext mDSLContext;

    protected MockMvc mMockMvc;

    /**
     * 家访详情-正常态
     */
    @Test
    public void getHomeVisitInfoSuccessfully() throws Exception {

        Long id = LongUtil.toLong(1);

        String jsonResponse = mMockMvc.perform(MockMvcRequestBuilders.get(BASE_HOST + "/api/admin/home/visit/" + id)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .sessionAttr(AUTHORIZED_ATTRIBUTE_NAME, getAuthSession()))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn().getResponse().getContentAsString();

        assertThatJson(jsonResponse).node("status").isEqualTo("success");
        assertThatJson(jsonResponse).node("data").isNotEqualTo(null);
        assertThatJson(jsonResponse).node("message").isEqualTo("");
        assertThatJson(jsonResponse).node("code").isEqualTo(0);

        assertThatJson(jsonResponse).node("data.id").isEqualTo(1);
        assertThatJson(jsonResponse).node("data.customerApplyNo").isEqualTo("customerApplyNo");
        assertThatJson(jsonResponse).node("data.customerName").isEqualTo("customerName");
        assertThatJson(jsonResponse).node("data.visitorName").isEqualTo("visitorName");
    }

    /**
     * 家访详情-家访id为null
     */
    @Test
    public void getHomeVisitInfoWhileIdIsNull() throws Exception {

        Long id = null;

        String jsonResponse = mMockMvc.perform(MockMvcRequestBuilders.get(BASE_HOST + "/api/admin/home/visit/" + id)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .sessionAttr(AUTHORIZED_ATTRIBUTE_NAME, getAuthSession()))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn().getResponse().getContentAsString();

        assertThatJson(jsonResponse).node("message").isEqualTo("参数id类型错误");
        assertThatJson(jsonResponse).node("status").isEqualTo("error");
        assertThatJson(jsonResponse).node("data").isEqualTo(null);
        assertThatJson(jsonResponse).node("code").isEqualTo(400);
    }

    /**
     * 家访详情-家访id小于或等于0
     */
    @Test
    public void getHomeVisitInfoWhileIdLessThanOrEqualToZero() throws Exception {

        Long id = LongUtil.toLong(0);

        String jsonResponse = mMockMvc.perform(MockMvcRequestBuilders.get(BASE_HOST + "/api/admin/home/visit/" + id)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .sessionAttr(AUTHORIZED_ATTRIBUTE_NAME, getAuthSession()))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn().getResponse().getContentAsString();
        assertThatJson(jsonResponse).node("message").isEqualTo("家访记录id参数错误");
        assertThatJson(jsonResponse).node("status").isEqualTo("error");
        assertThatJson(jsonResponse).node("data").isEqualTo(null);
        assertThatJson(jsonResponse).node("code").isEqualTo(400);
    }

}

解释说明:

@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest
@Transactional
@Sql("classpath:/sql/admin/homevisit/getHomeVisitInfoTests.sql")

有关这5个注解的作用可参考 单元测试Junit Test 中 Assertions 使用  文末介绍,这里不再赘述。

接下来,重点讲解聚焦Controller的测试模板代码块:

Long id = LongUtil.toLong(1);

String jsonResponse = mMockMvc.perform(MockMvcRequestBuilders.get(BASE_HOST + "/api/admin/home/visit/" + id)    --1
                .contentType(MediaType.APPLICATION_JSON_UTF8)                 --2
                .sessionAttr(AUTHORIZED_ATTRIBUTE_NAME, getAuthSession()))    --3
                .andExpect(MockMvcResultMatchers.status().isOk())             --4
                .andDo(MockMvcResultHandlers.print())                         --5
                .andReturn().getResponse().getContentAsString();              --6


1:构建API URL

2:设置Media类型为 Json utf-8

3:设置Cookie(可选)

4:Api请求期望状态码,比如200代表成功响应

5:打印接口响应信息

6:抽取接口响应的数据字符串


1~6都是一个套路。接着就是按需校验接口响应结果是否符合预期!