SpringBoot测试类编写

前置要求:

a.测试类上需要的注解

@SpringBootTest
@AutoConfigureMockMvc
@Slf4j

 b.引入MockMvc类

@Autowired
private MockMvc mockMvc;

c.如果需要前置条件可以用before注解

 

        1.get/delete请求

    // 查询
    @Test
    void testQuery() throws Exception {
        String content = mockMvc.perform(get("/api/v1/test/list") // 查询请求地址
                .param("param1", "...") // 参数(可以多个,如下)
                .param("param2", "...")
                .header("Authorization", "Bearer " + token) // 增加header参数
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk()) // 查询为成功状态才会运行后续方法(.andReturn().getResponse().getContentAsString())
                .andReturn().getResponse() // 获取返回数据(封装的全数据)
                .getContentAsString(); // 获取返回的的content,就是String结果集
        // 格式化打印查询结果
        log.info("content:{}", JSONUtil.parse(content).toStringPretty());
    }


    // 删除
    @Test
    void testDelete() throws Exception {
        String id = "xxxxxxx";
        String content = mockMvc.perform(delete("/api/v1/test/"+ id) // 查询请求地址
                .header("Authorization", "Bearer " + token) // 增加header参数
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk()) // 查询为成功状态才会运行后续方法(.andReturn().getResponse().getContentAsString())
                .andReturn().getResponse() // 获取返回数据(封装的全数据)
                .getContentAsString(); // 获取返回的的content,就是String结果集
        // 格式化打印查询结果
        log.info("content:{}", JSONUtil.parse(content).toStringPretty());
    }

        

方法解析:

  • perform执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理;
  • get:声明发送一个get请求的方法。MockHttpServletRequestBuilder get(String urlTemplate, Object... urlVariables):根据uri模板和uri变量值得到一个GET请求方式的。另外提供了其他的请求的方法,如:post、put、delete等。
  • param:添加request的参数,如上面发送请求的时候带上了了pcode = root的参数。假如使用需要发送json数据格式的时将不能使用这种方式,可见后面被@ResponseBody注解参数的解决方法
  • andExpect:添加ResultMatcher验证规则,验证控制器执行完成结果是否正确(对返回的数据进行的判断);
  • andDo:添加ResultHandler结果处理器,比如调试时打印结果到控制台(对返回的数据进行的判断);
  • andReturn:最后返回相应的MvcResult;然后进行自定义验证/进行下一步的异步处理(对返回的数据进行的判断);

2.post请求

        注意要标注传参类型(.contentType(MediaType.APPLICATION_JSON) 

    /**
     * 新增
     *
     * @Throws Exception
     */
    @Test
    void testSave() throws Exception {
        /**
         * java代码为这样的接口:
         * @Operation(description = "保存", summary = "保存")
         * @PostMapping("/record")
         * public void save(@Validated @RequestBody CheckRoomDto.SaveReqDto req) {
         *
         * }
         */
        // 构建请求 CheckRoomDto.SaveReqDto req
        CheckRoomDto.SaveReqDto req = new CheckRoomDto.SaveReqDto();
        req.setCheckRoomTime(new Date());
        mockMvc.perform(post("/api/v1/test/record/")
                .contentType(MediaType.APPLICATION_JSON) // 标注传参类型,application/json
                .content(JSONUtil.toJsonStr(req)) // 将dto转换成json格式字符串放到content里面
                .header("Authorization", "Bearer " + token)
                .accept(MediaType.APPLICATION_JSON)) // 接受的数据的数据格式
                .andExpect(status().isOk())
                .andReturn().getResponse();// 新增一般没有返回值,如果有,打印同get请求
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot 提供了多种测试注解和工具,可以方便地编写测试。下面是一些常用的测试示例: 1. 单元测试 单元测试是用来测试单个或方法是否符合预期的,通常不需要启动 Spring 应用。 ```java import org.junit.Test; import static org.junit.Assert.assertEquals; public class MyTest { @Test public void test() { assertEquals(2, 1 + 1); } } ``` 2. 集成测试 集成测试是用来测试应用的各个组件是否能够协同工作,通常需要启动 Spring 应用。 ```java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class MyTest { @Autowired private MyService myService; @Test public void test() { myService.doSomething(); // 测试代码 } } ``` 3. Web测试 Web 测试是用来测试 Web 应用的,通常需要启动 Spring 应用,并使用 Spring Boot 提供的测试工具进行测试。 ```java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class MyTest { @Autowired private MockMvc mockMvc; @Test public void test() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/hello")) .andExpect(MockMvcResultMatchers.status().isOk()); } } ``` 在这个示例中,`@AutoConfigureMockMvc` 注解会自动配置一个 `MockMvc` 对象,用于模拟 HTTP 请求和响应。`mockMvc.perform()` 方法可以发送 HTTP 请求,`.andExpect()` 方法可以验证 HTTP 响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月存5k的欢乐外包仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值