junit-mock-controller

2023-12-22 18:41:37

BaseTest

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

?

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

文章来源:https://blog.csdn.net/luohaihua_20/article/details/127432700
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。