SpringBoot使用MockMvc对Controller层进行单元测试

Mockito是GitHub上使用最广泛的Mocking框架。它提供简洁的API来测试。Mockito简单易学、可读性强、验证语法简洁。

【示例】使用Mockito框架,对Controller层进行单元测试。

创建UserController(用户信息控制器)。

package com.pjb.controller;
 
import com.pjb.entity.UserInfo;
import com.pjb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
/**
 * 用户信息控制器
 * @author pan_junbiao
 **/
@RestController
@RequestMapping("user")
public class UserController
{
    @Autowired
    private UserService userService;
 
    /**
     * 获取用户信息
     * RESTful接口
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public UserInfo getUserInfo(@PathVariable("id")int userId)
    {
        UserInfo userInfo = userService.getUserInfoById(userId);
        return userInfo;
    }
 
    /**
     * 根据用户ID,获取用户信息
     */
    @RequestMapping("/getUserInfoById")
    public UserInfo getUserInfoById(@RequestParam(value = "user_id", defaultValue = "0") int userId)
    {
        UserInfo userInfo = userService.getUserInfoById(userId);
        return userInfo;
    }
 
    /**
     * 新增用户信息
     * 参数:接收对象型参数
     */
    @RequestMapping(value = "/addUserByEntity", method = RequestMethod.POST)
    public boolean addUserByEntity(@RequestBody UserInfo userInfo)
    {
        boolean result = userService.addUser(userInfo);
        return result;
    }
 
    /**
     * 新增用户信息
     * 参数:接收多个参数
     */
    @RequestMapping(value = "/addUserByParam", method = RequestMethod.POST)
    public boolean addUserByParam(String userName,String blogUrl,String blogRemark)
    {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(userName);
        userInfo.setBlogUrl(blogUrl);
        userInfo.setBlogRemark(blogRemark);
 
        boolean result = userService.addUser(userInfo);
        return result;
    }
}

(2)实现Controller层的单元测试。

package com.pjb.controller;
 
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pjb.entity.UserInfo;
import org.junit.Assert;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;
 
/**
 * 用户信息控制器测试类
 * @author pan_junbiao
 **/
@SpringBootTest
@RunWith(SpringRunner.class)
class UserControllerTest
{
    //启用Web上下文
    @Autowired
    private WebApplicationContext webApplicationContext;
 
    private MockMvc mockMvc;
 
    @BeforeEach
    private void setUp()
    {
        //使用上下文构建MockMvc
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }
 
    @AfterEach
    private void tearDown()
    {
    }
 
    /**
     * 根据用户ID,获取用户信息
     * RESTful接口
     */
    @Test
    public void getUserInfo() throws Exception
    {
        //执行请求(使用GET请求,RESTful接口)
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/user/{id}",1).accept(MediaType.APPLICATION_JSON_UTF8)).andReturn();
 
        //获取返回编码
        int status = mvcResult.getResponse().getStatus();
 
        //获取返回结果
        String content = mvcResult.getResponse().getContentAsString();
 
        //断言,判断返回编码是否正确
        Assert.assertEquals(200,status);
 
        //将JSON转换为对象
        ObjectMapper mapper = new ObjectMapper();
        UserInfo  userInfo = mapper.readValue(content, UserInfo.class);
 
        //打印结果
        System.out.println("用户ID:" + userInfo.getUserId());
        System.out.println("用户姓名:" + userInfo.getUserName());
        System.out.println("博客地址:" + userInfo.getBlogUrl());
        System.out.println("博客信息:" + userInfo.getBlogRemark());
    }
 
    /**
     * 根据用户ID,获取用户信息
     * 使用GET请求
     */
    @Test
    public void getUserInfoById() throws Exception
    {
        //执行请求(使用GET请求)
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/user/getUserInfoById").param("user_id","1").accept(MediaType.APPLICATION_JSON_UTF8)).andReturn();
 
        //获取返回编码
        int status = mvcResult.getResponse().getStatus();
 
        //获取返回结果
        String content = mvcResult.getResponse().getContentAsString();
 
        //断言,判断返回编码是否正确
        Assert.assertEquals(200,status);
 
        //将JSON转换为对象
        ObjectMapper mapper = new ObjectMapper();
        UserInfo  userInfo = mapper.readValue(content, UserInfo.class);
 
        //打印结果
        System.out.println("用户ID:" + userInfo.getUserId());
        System.out.println("用户姓名:" + userInfo.getUserName());
        System.out.println("博客地址:" + userInfo.getBlogUrl());
        System.out.println("博客信息:" + userInfo.getBlogRemark());
    }
 
    /**
     * 新增用户信息
     * 使用POST请求,传递对象型参数
     */
    @Test
    public void addUserByEntity() throws Exception
    {
        //创建新用户
        UserInfo userParam = new UserInfo();
        userParam.setUserName("pan_junbiao的博客");
        userParam.setBlogUrl("https://blog.csdn.net/pan_junbiao");
        userParam.setBlogRemark("您好,欢迎访问 pan_junbiao的博客");
 
        //将参数转换成JSON对象
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(userParam);
 
        //执行请求(使用POST请求,传递对象参数)
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/user/addUserByEntity").content(json).contentType(MediaType.APPLICATION_JSON)).andReturn();
 
        //获取返回编码
        int status = mvcResult.getResponse().getStatus();
 
        //获取返回结果
        String content = mvcResult.getResponse().getContentAsString();
 
        //断言,判断返回编码是否正确
        Assert.assertEquals(200,status);
 
        //断言,判断返回结果是否正确
        Assert.assertEquals("true",content);
    }
 
    /**
     * 多个参数的传递
     * 使用POST请求,传递多个参数
     */
    @Test
    public void addUserByParam() throws Exception
    {
        //多个参数的传递
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("userName","pan_junbiao的博客");
        params.add("blogUrl","https://blog.csdn.net/pan_junbiao");
        params.add("blogRemark","您好,欢迎访问 pan_junbiao的博客");
 
        //执行请求(使用POST请求,传递多个参数)
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/user/addUserByParam").params(params)).andReturn();
 
        //获取返回编码
        int status = mvcResult.getResponse().getStatus();
 
        //获取返回结果
        String content = mvcResult.getResponse().getContentAsString();
 
        //断言,判断返回编码是否正确
        Assert.assertEquals(200,status);
 
        //断言,判断返回结果是否正确
        Assert.assertEquals("true",content);
    }
}

执行结果:

 

  • 10
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
在Spring Boot中,可以使用JUnit和MockMvc进行Controller单元测试。下面是一个示例: ```java import org.junit.Before; 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.http.MediaType; 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 MyControllerTest { @Autowired private MockMvc mockMvc; @Before public void setup() { // 在每个测试方法执行前的初始化操作 } @Test public void testController() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/mycontroller") .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.name").value("John")) .andExpect(MockMvcResultMatchers.jsonPath("$.age").value(25)); } } ``` 上述代码中,我们使用了`@RunWith(SpringRunner.class)`注解来指定使用SpringRunner运行测试。`@SpringBootTest`注解用于加载Spring Boot应用程序上下文。`@AutoConfigureMockMvc`注解用于自动配置MockMvc实例。 在`testController`方法中,我们使用`MockMvc`执行了一个GET请求,并验证了返回的状态码和JSON响应的内容。 需要注意的是,上述示例中的路径`/api/mycontroller`和JSON响应的内容`name`和`age`是根据具体的Controller和返回值来设置的,你需要根据你的实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

pan_junbiao

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

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

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

打赏作者

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

抵扣说明:

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

余额充值