junit-mock-controller

BaseTest

java 复制代码
package com.xxxxx.xxx;

import org.codehaus.jackson.map.ObjectMapper;
import org.junit.runner.RunWith;
import org.springframework.http.HttpHeaders;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
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.result.MockMvcResultMatchers;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 单元测试基类
 * @author: luohh
 * @time: 2022/4/14 16:09
 */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath*:dubbo_config/*.xml", "classpath*:spring-jpa.xml"})
@WebAppConfiguration  //不用启动 Servlet 容器,就可以获取一个 Web 应用上下文
public class BaseTest {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    protected Map<String,String> params = new HashMap<>();
    protected Map<String,String> headers = new HashMap<>();
    protected  MockMvc mockMvc;

    /**
     * POST请求
     * @param url
     * @return
     * @throws Exception
     */
    protected Map<String, String> postHttp(String url) throws Exception{
        MultiValueMap<String,String> multiValueParamMap = new LinkedMultiValueMap<>();
        if (params.size() > 0){
            multiValueParamMap.setAll(params);
        }
        HttpHeaders httpHeaders = new HttpHeaders();
        if (headers.size() > 0){
           for (String key :headers.keySet()){
               httpHeaders.set(key, headers.get(key));
           }
        }
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders
                .post(url)
                .params(multiValueParamMap)
                .headers(httpHeaders))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn();
        mvcResult.getResponse().setCharacterEncoding("UTF-8");
        mvcResult.getResponse().setContentType("application/json;charset=UTF-8");
        String result = mvcResult.getResponse().getContentAsString();

        Map<String, String> map = MAPPER.readValue(result, Map.class);
        return map;
    }

    /**
     * GET请求
     * @param url
     * @return
     * @throws Exception
     */
    protected Map<String, String> getHttp(String url) throws Exception{
        MultiValueMap<String,String> multiValueParamMap = new LinkedMultiValueMap<>();
        if (params.size() > 0){
            multiValueParamMap.setAll(params);
        }
        HttpHeaders httpHeaders = new HttpHeaders();
        if (headers.size() > 0){
            for (String key :headers.keySet()){
                httpHeaders.set(key, headers.get(key));
            }
        }
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders
                .get(url)
                .params(multiValueParamMap)
                .headers(httpHeaders))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn();
        mvcResult.getResponse().setCharacterEncoding("UTF-8");
        mvcResult.getResponse().setContentType("application/json;charset=UTF-8");
        String result = mvcResult.getResponse().getContentAsString();

        Map<String, String> map = MAPPER.readValue(result, Map.class);
        return map;
    }
}

Controller

java 复制代码
package com.xxxxxx.xxx.web.controller;

import com.xxxxxx.xxx.BaseTest;
import com.xxxxxx.xxx.xx.service.UserService;
import com.xxxxxx.xxx.web.base.constants.Constants;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.api.support.membermodification.MemberMatcher;
import org.powermock.api.support.membermodification.MemberModifier;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import java.util.Map;

/**
 * @author luohh
 * @date 2023/12/20 15:30
 */
public class UserControllerTest extends BaseTest {

    private static final String REQUEST_URL_PREFIX = "/api/user";
    private String key = "5368C8B07450DE28F064BEDE4A96229C";
    private String token = "";
private String userId = "123456";
    @InjectMocks // 用于创建一个实例,调用其真实的方法
    private UserController userController;
    @Mock
    private UserService userService;

    @Before
    public void setup() throws Exception {
        MockitoAnnotations.initMocks(this);
        // 初始化mockMvc
        this.mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
        token = "YrJKoFhDH2kazS2WjJbq8A==";
    }
    @Test
    public void testUserWithValidate() throws Exception {
        Mockito.when(userService.findByUserId(Mockito.anyLong())).thenReturn(null);
        params.put("userId",userId);
        headers.put("token",token);
        Map<String, String> map = postHttp(REQUEST_URL_PREFIX + "/authUser");
        Assert.assertEquals("用户已作废", map.get("message"));
        Mockito.when(userService.findByUserId(Mockito.anyLong())).thenReturn(new User());
        headers.clear();
        map = postHttp(REQUEST_URL_PREFIX + "/authUser");
        Assert.assertEquals("您没有权限调用该接口", map.get("message"));
        headers.put("token",token+1);
        map = postHttp(REQUEST_URL_PREFIX + "/authUser");
        Assert.assertEquals("权限校验失败", map.get("message"));
    }
}
相关推荐
字节程序员4 天前
使用JUnit进行集成测试
jmeter·junit·单元测试·集成测试·压力测试
两水先木示6 天前
【Unity3D】无限循环列表(扩展版)
java·开发语言·junit
小白学大数据6 天前
优化Lua-cURL:减少网络请求延迟的实用方法
开发语言·网络·爬虫·junit·lua
璀若星辰6 天前
Spring Boot 项目中 JUnit 使用总结
spring boot·后端·junit
烟草的香味.7 天前
nginx 记录完整的 request 及 response
java·nginx·junit
小诸葛的博客7 天前
wrk如何测试post请求
junit
睡睡怪9 天前
【Java学习笔记】JUnit
笔记·学习·junit
小白学大数据15 天前
Lua中实现HTTP请求的User-Agent自定义
爬虫·http·junit·数据分析·lua
帅B猪15 天前
Lua面向对象 实现 超详细注释 实现构造函数,析构函数,只读类模板等功能
java·c++·算法·junit·lua
爱代码的猴子15 天前
【记录】用JUnit 4的@Test注解时报错java.lang.NullPointerException的原因与解决方法
java·数据库·junit