junit mockito不启动服务

2023-12-28 16:57:54

不启动服务的优缺点

  • 没有启时服务的耗时,执行单元测试快
  • 不依懒第三方服务(如dubbo,数据库,redis)

启动服务优缺点

  • 启动spring容器,加截spring配置,方便各种依懒环境调试(比如数据库)
  • 启动spring容器耗时,随着项目的复杂,启动要几分钟

MockBaseTest

?
package com.xxxxxxx.xxx;

import com.xxxxxxx.xxx.web.base.controller.JsonResponse;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.HttpHeaders;
import org.springframework.test.context.ActiveProfiles;
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: 2023/12/14 16:09
 */

@RunWith(MockitoJUnitRunner.class)
@ActiveProfiles("dev")
public class MockBaseTest {
    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 JsonResponse 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();
        return MAPPER.readValue(result, JsonResponse.class);
    }

    /**
     * GET请求
     * @param url
     * @return
     * @throws Exception
     */
    protected JsonResponse 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();
        return MAPPER.readValue(result, JsonResponse.class);
    }
}


?

TestController

package com.xxxxxxx.xxx.web.controller;

import com.xxxxxxx.xxx.service.CustService;
import com.xxxxxxx.xxx.MockBaseTest;
import com.xxxxxxx.xxx.web.base.controller.JsonResponse;
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.springframework.test.web.servlet.setup.MockMvcBuilders;

/**
 * 用户反馈单元测试
 */
public class BackControllerTest extends MockBaseTest {

    private static final String PREFIX = "/api/back";
    @InjectMocks
    private BackController backController;
    @Mock
    private CustService custService;
    @Before
    public void init() throws Exception {
        MockitoAnnotations.initMocks(this);
        // 初始化mockMvc
        this.mockMvc = MockMvcBuilders.standaloneSetup(backController).build();
    }

    @Test
    public void testCreateBackWithParam_success() throws Exception {
        params.put("content", "XXXXXX");
        params.put("version", "1.0..0");
        params.put("phone", "19911111111");
        Mockito.when(custService.createBack(Mockito.anyObject())).thenReturn(true);
        JsonResponse response = postHttp(PREFIX + "/create_back");
        Assert.assertEquals(response.getMessage(), "已反馈!");
    }
}

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