Spring Boot Controller层测试

概述


对业务Service层的代码进行详尽的单元测试是非常必要的,但也不能忽视Controller层的测试,毕竟Controller层的接口输出
都是给前端用的,且Controller层拿到业务Service层的返回结果后,通常也会做一些业务处理或者转换的问题,以适配前端的展示需求。

目前参与的项目,都是基于Spring Boot的,下面就简单介绍一下如何基于Spring Boot 2'Junit 5 进行Controller 层测试。之前已经写过一篇

SpringBoot Controller Post接口单元测试

的文章,这次做一个简单的补充:

  • 如何调用Controller层的get方法;
  • 详细一些的例子

JAR包版本


spring boot

2.0.4.RELEASE

大版本定了后,就可以像下面这样,引入Spring Boot TestWeb了。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

junit

         <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.1.1</version>
            <scope>test</scope>
         </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.1.1</version>
            <scope>test</scope>
        </dependency>

版本用的是5.1.1

FastJson

     <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.47</version>
    </dependency>

Demo


HelloController

@RestController
@RequestMapping(value = "hello")
public class HelloController {

     @RequestMapping(value = "/create", method = RequestMethod.POST)
     String create(@RequestBody(required = false) HelloCreateReq helloCreateReq) {
         String msg = helloCreateReq.getMsg();
         Integer userId = helloCreateReq.getUserId();
         return "msg:"+msg+",userId:"+userId;
     }
}

HelloControllerTest

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment =SpringBootTest.WebEnvironment.MOCK,classes = TestApplication.class)
@AutoConfigureMockMvc
public class HelloControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    @DisplayName("测试controller post方法")
    void helloCreate() throws Exception {
        HelloCreateReq req = new HelloCreateReq();
        req.setMsg("test hello create");
        req.setUserId(123);
        MvcResult mvcResult = mockMvc.
                perform(
                        post("/hello/create")
                                .contentType(MediaType.APPLICATION_JSON)
                                .content(JSON.toJSONString(req)))
                .andReturn();
        System.out.println(mvcResult.getResponse().getContentAsString());
    }
}

直接执行helloCreate()方法,就可以调用到Controller的方法了。由于Spring Boot下跑单元测试的时候,需要一个Application,因此我们需要简单的构造一下。

/**
 * 由于是基于spring boot test组件进行单元测试,需要构建一个TestApplication上下文
 */
@SpringBootApplication
public class TestApplication {

    public static void main(String[] args){
        SpringApplicationBuilder builder = new SpringApplicationBuilder();
        builder.environment(new StandardEnvironment());
        builder.sources(TestApplication.class);
        builder.main(TestApplication.class);
        builder.run(args);
    }
}

如果想调用Controller层的get方法,也很简单。

@RestController
@RequestMapping(value = "hello")
public class HelloController {

    @RequestMapping(value = "/getMsg", method = RequestMethod.GET)
    Integer getMsg(Integer userId) {
        return userId;
    }
}

对应的test方法。

    @Test
    @DisplayName("测试controller get方法")
    void getMsg() throws Exception {
        MvcResult mvcResult = mockMvc.perform(get("/hello/getMsg?userId=123")).andReturn();
        System.out.println(mvcResult.getResponse().getContentAsString());
    }

总结


本文只是简单介绍一下基础用法,像mock技术、验证返回结果、异常处理等手法没有介绍到,留到下次讲Service层单元测试的时候,再补充。

猜你喜欢

转载自blog.csdn.net/linsongbin1/article/details/100591097