Spring Boot Controller层测试

本文介绍如何使用SpringBoot2和Junit5进行Controller层的单元测试,包括调用POST和GET方法的具体步骤,适用于基于SpringBoot框架的项目。

概述


对业务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层单元测试的时候,再补充。

### Spring BootController的作用及功能介绍 在Spring Boot框架中,Controller是应用程序的核心组件之一,主要用于处理HTTP请求和响应。以下是关于Controller作用及功能的详细介绍: #### 1. 请求映射 Controller通过注解将特定的URL路径与方法绑定在一起,从而实现对HTTP请求的接收和处理。例如,`@RequestMapping`、`@GetMapping`、`@PostMapping`等注解可以指定请求的方式和路径[^1]。 #### 2. 数据交互 Controller负责将前端传来的数据传递给Service进行业务逻辑处理,并将Service返回的结果以适当的形式(如JSON或HTML)返回给客户端。对于RESTful风格的应用程序,通常使用`@RestController`注解来简化数据交互过程[^2]。 #### 3. 注解区分 Spring Boot提供了两种主要的控制器注解: - `@Controller`:用于传统的MVC模式,返回视图名称(如JSP或Thymeleaf模板),并结合视图解析器渲染页面。 - `@RestController`:专为RESTful API设计,直接返回数据(如JSON或XML格式),无需视图解析[^3]。 #### 4. 级关系 Controller作为应用的入口点,与Service紧密协作。当接收到客户端请求时,Controller会调用Service的方法进行业务逻辑处理。Service完成后,Controller将结果返回给客户端[^4]。 #### 5. 示例代码 以下是一个典型的Controller实现示例,展示了如何处理增删改查操作: ```java package Controller.Goods; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import pojo.Goods; import service.Goods.GoodsService; @Controller public class GoodsControllerImpl { @Autowired private GoodsService goodsService; @RequestMapping(value = "/insertGoods") public String insertGoods(Goods goods) throws Exception { goodsService.insertGoods(goods); return "redirect:/index"; } @RequestMapping(value = "/deleteGoods") public String deleteGoods(String GNo) throws Exception { goodsService.deleteGoods(GNo); return "redirect:/index"; } @RequestMapping(value = "/updateGoods") public String updateGoods(Goods goods) throws Exception { goodsService.updateGood(goods); return "redirect:/index"; } @RequestMapping(value = "/findGoods") public String findByGNo(String GNo) throws Exception { Goods goods = goodsService.findByGNo(GNo); // 进一步处理goods对象 return "goodsDetails"; } } ``` 上述代码展示了如何通过Controller调用Service完成商品相关的增删改查操作[^5]。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值