侧边栏壁纸
  • 累计撰写 57 篇文章
  • 累计创建 23 个标签
  • 累计收到 4 条评论

SpringBoot UT测试

cluski
2022-03-22 / 0 评论 / 0 点赞 / 146 阅读 / 4,863 字
温馨提示:
本文最后更新于 2022-03-22,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

UT测试

TODO:

  1. 各层的模拟

    • Controller层
    • Service层
    • Mapper层

    每层并不是需要一定需要单独分开来模拟,如果在数据可以轻松造出来的前提的话,可以一条线最后走到Mapper层再返回。而在UT的时候,可以使用H2数据库来模拟数据,并且使用@Profile注解来指定本次的需要用到什么配置文件(从而来决定使用什么sql文件)

  2. 覆盖率测试

1、各层的模拟

https://www.jianshu.com/p/ecbd7b5a2021

https://www.jianshu.com/p/9387e27ab5e5

1.1、Controller层

参考文档:

Testing with a mock environment

一般来说我们Controller会有这么几种传参的方式:

  • GET、params传参
  • GET、 @Pathvariable 路径参数提交
  • POST、JSON传参
  • POST、form传参
package com.example.utdemo.controller;

import com.example.utdemo.domain.User;
import com.example.utdemo.service.TestService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName TestController
 * @Description test controller
 * @Author wangyf
 * @Date 2022/3/22 17:48
 * @Version 1.0
 */
@RestController()
@RequestMapping("/test")
public class TestController {
    /**
     * Get 请求, params 参数提交
     *
     * @param a
     * @param b
     * @return
     */
    @GetMapping(value = "/get")
    public String getParams(String a, String b) {
        return "TestController" + a + b;
    }

    /**
     * Get 请求, @Pathvariable 路径参数提交
     *
     * @param page
     * @param size
     * @param name
     * @return
     */
    @GetMapping(value = "/get/{page}/{size}")
    public String getPathVariable(@PathVariable String page, @PathVariable String size, String name) {
        return "TestController" + page + size + name;
    }

    /**
     * post 请求,json 数据提交
     *
     * @param user
     * @return
     */
    @PostMapping("/postJson")
    public String postJson(@RequestBody User user) {
        return "TestController:postJson:" + user.toString();
    }

    /**
     * post 请求,from 数据提交
     *
     * @param user
     * @return
     */
    @PostMapping("/postForm")
    public String postForm(User user) {
        return "TestController:postForm:" + user.toString();
    }
}

为了可以模拟出对应的请求,我们可以用到Sprintboot test中的MockMvc:

package com.example.utdemo.controller;

import cn.hutool.json.JSONUtil;
import com.example.utdemo.domain.User;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import javax.annotation.Resource;
import java.net.URI;

/**
 * @ClassName TestControllerTests
 * @Description TODO
 * @Author wangyf
 * @Date 2022/3/22 21:39
 * @Version 1.0
 */
@SpringBootTest
@AutoConfigureMockMvc
public class TestControllerTests {

    @Resource
    MockMvc mockMvc;

    /**
     * Get 请求, params 参数提交
     */
    @Test
    @SneakyThrows
    public void getParamsTest() {
        ResultActions perform = mockMvc.perform(MockMvcRequestBuilders
//                .get("/test/get?a={a}&b={b}", "hello", "world"));
                .get(new URI("/test/get"))
                .param("a", "hello")
                .param("b", "world"));
        perform.andExpect(MockMvcResultMatchers.status().isOk());
        MvcResult mvcResult = perform.andReturn();
        Assertions.assertEquals("TestControllerhelloworld", mvcResult.getResponse().getContentAsString());
    }

    /**
     * Get 请求, @Pathvariable 路径参数提交
     */
    @Test
    @SneakyThrows
    public void getPathVariableTest() {
        ResultActions perform = mockMvc.perform(MockMvcRequestBuilders
                .get("/test/get/{page}/{size}", "1", "2")
                .param("name", "wyf"));
        perform.andExpect(MockMvcResultMatchers.status().isOk());
        MvcResult mvcResult = perform.andReturn();
        Assertions.assertEquals("TestController12wyf", mvcResult.getResponse().getContentAsString());
    }

    /**
     * post 请求,json 数据提交
     */
    @Test
    @SneakyThrows
    public void postJsonTest() {
        User wyf = User.builder().name("wyf").age(18).email("123@123.com").build();
        ResultActions perform = mockMvc.perform(MockMvcRequestBuilders
                .post(new URI("/test/postJson"))
                .content(JSONUtil.parse(wyf).toString())
                .contentType(MediaType.APPLICATION_JSON));
        perform.andExpect(MockMvcResultMatchers.status().isOk());
        MvcResult mvcResult = perform.andReturn();
        Assertions.assertEquals("TestController:postJson:" + wyf.toString(), mvcResult.getResponse().getContentAsString());
    }

    /**
     * post 请求,from 数据提交
     */
    @Test
    @SneakyThrows
    public void postFormTest() {
        User wyf = User.builder().name("wyf").age(18).email("123@123.com").build();
        ResultActions perform = mockMvc.perform(MockMvcRequestBuilders
                .post(new URI("/test/postForm"))
                .param("name", "wyf")
                .param("age", "18")
                .param("email", "123@123.com")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED));
        perform.andExpect(MockMvcResultMatchers.status().isOk());
        MvcResult mvcResult = perform.andReturn();
        Assertions.assertEquals("TestController:postForm:" + wyf.toString(), mvcResult.getResponse().getContentAsString());
    }

}

需要进行以下几点:

  1. 在测试类上使用@AutoConfigureMockMvc注解,启用和配置MockMvc。
  2. 动态注入Mockvc对象
  3. 构建ResultActions对象,进行http调用
  4. 判断返回结果

2.2、Service层

0

评论区