针对Controller的单元自测

本文介绍如何使用Spring Boot进行单元测试,包括配置依赖、执行GET/POST请求测试、处理多参数及自定义实体请求,还涉及文件上传接口的测试方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<!-- 新增,用于单元自测 -->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.6.2</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

普通请求(get/post):

@Transactional // 有数据库操作则自动回滚
@Test
void test() throws Exception {
    mvc.perform(MockMvcRequestBuilders.get("/xxx/xxx")
            .accept(MediaType.APPLICATION_JSON)
            .param("key", "value"))
            .andExpect(MockMvcResultMatchers.status().isOk()) // 期望的状态码
         .andExpect(MockMvcResultMatchers.jsonPath("$.code") // 期望返回体中自定义code的值
         .value(200))   .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("success")) // 同上
            .andDo(MockMvcResultHandlers.print()); // 打印请求和返回
}

多个参数:

MultiValueMap queryMap = new LinkedMultiValueMap();
queryMap.add("key1", "value1");
queryMap.add("key2", "value2");
queryMap.add("key3", "value3");

mvc.perform(MockMvcRequestBuilders.post("/xxx/xxx")
        .params(queryMap))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.jsonPath("$.code").value(200))
        .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("success"))
        .andDo(MockMvcResultHandlers.print());

自定义实体@RequestBoy接受:

CustomBean bean = new CustomBean();
bean.setProp1("v1");
bean.setProp2("v2");
String json = JSONObject.toJSONString(bean);
mvc.perform(MockMvcRequestBuilders.post("/xxx/xxx")
        .contentType(MediaType.APPLICATION_JSON)
        .content(json)
        .characterEncoding("UTF-8"))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.jsonPath("$.code").value(200))
        .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("success"))
        .andDo(MockMvcResultHandlers.print());

文件接口:

    @Transactional
    @Test
    void testImportHistoryTest() throws Exception {
        MockMultipartFile multipartFile = buildMockMultipartFile();

        mvc.perform(MockMvcRequestBuilders.multipart("/xxx/xxx")
                .file(multipartFile).param("key", "val")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
              .andExpect(MockMvcResultMatchers.jsonPath("$.code").value(200))           .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("success"))
                .andDo(MockMvcResultHandlers.print());
    }
private MockMultipartFile buildMockMultipartFile() throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("sheet1");

        for(int i = 0; i <= 5; i ++) {
            HSSFRow row1 = sheet.createRow(i);
            HSSFCell accountCell = row1.createCell(0);
            accountCell.setCellType(CellType.STRING);
            accountCell.setCellValue("col0");

            HSSFCell typeCell = row1.createCell(1);
            typeCell.setCellType(CellType.STRING);
            typeCell.setCellValue("col1");

            HSSFCell valueCell = row1.createCell(2);
            valueCell.setCellType(CellType.STRING);
            valueCell.setCellValue("col2");
        }

        File file = new File("test.xls");
        FileOutputStream fos = new FileOutputStream(file);
        workbook.write(fos);
        fos.close();

        FileInputStream fis = new FileInputStream(file);
        MockMultipartFile multipartFile = new MockMultipartFile("file", "test.xls", MediaType.TEXT_PLAIN_VALUE,fis);

        return multipartFile;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值