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"));
    }
}
相关推荐
风霜不见闲沉月3 天前
kong网关的使用
junit·kong
一名技术极客4 天前
Nginx 实现动态封禁IP,详细教程来了
tcp/ip·nginx·junit
菠萝地亚狂想曲4 天前
优雅的LUA数据记录方法-serpent序列化+LUA Table
开发语言·junit·lua
硬汉嵌入式5 天前
H7-TOOL的LUA小程序教程第17期:扩展驱动AD7606, ADS1256,MCP3421, 8路继电器和5路DS18B20(2024-11-01)
junit·小程序·lua
程序猿小D6 天前
第三百零六节 Log4j教程 - Log4j日志级别
junit·单元测试·log4j
A尘埃6 天前
单元测试(Junit)
junit·单元测试·log4j
lihan_freak7 天前
Spring框架---IOC注解方式,Spring整合Junit单元测试
spring·junit·单元测试
程序猿小D8 天前
第三百零五节 Log4j教程 - Log4j日志记录方法
java·sql·junit·单元测试·log4j·mybatis·lucene
又菜又爱玩的晴晴8 天前
mockito+junit完成单元测试
junit·单元测试·mockito
板子小哥8 天前
LuatOS学习指南:开启物联网开发之旅
运维·服务器·开发语言·人工智能·物联网·junit·lua