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 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);
    }
}

执行结果:

SpringBoot使用MockMvc对Controller层进行单元测试_第1张图片

 

你可能感兴趣的:(#,Spring,Boot,我の原创)