junit mockito Base基类

编写单元测试时我们都习惯性减少重复代码

以下基于spring mvc框架,需要手动pom导包

BaseTest类用于启动上下文进行debug调试

MockBaseTset类用于不启动上下文进行打桩mock

pom.xml

XML 复制代码
      <dependency>
		  <groupId>org.mockito</groupId>
		  <artifactId>mockito-all</artifactId>
		  <version>1.9.5</version>
		  <scope>test</scope>
	  </dependency>

	  <dependency>
		  <groupId>org.powermock</groupId>
		  <artifactId>powermock-api-mockito</artifactId>
		  <version>1.6.1</version>
		  <scope>test</scope>
	  </dependency>
	  <dependency>
		  <groupId>org.powermock</groupId>
		  <artifactId>powermock-module-junit4</artifactId>
		  <version>1.6.1</version>
		  <scope>test</scope>
	  </dependency>
	 
	  <dependency>
		  <groupId>org.springframework</groupId>
		  <artifactId>spring-test</artifactId>
		  <version> 4.2.5.RELEASE</version>
		  <scope>test</scope>
		  <exclusions>
			  <exclusion>
				  <groupId>commons-logging</groupId>
				  <artifactId>commons-logging</artifactId>
			  </exclusion>
		  </exclusions>
	  </dependency>
	  <dependency>
		  <groupId>junit</groupId>
		  <artifactId>junit</artifactId>
		  <scope>test</scope>
	  </dependency>

BaseTest.java

java 复制代码
import com.thinkive.gateway.v2.result.Result;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
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: 单元测试基类
 */

@RunWith(SpringJUnit4ClassRunner.class)
//解决@Slf4j报错
@PowerMockIgnore({"javax.script.*","javax.management.*"}) 
@ContextConfiguration({"classpath*:dubbo_cfg/*.xml", "classpath*:spring-cfg.xml"})
//不用启动 Servlet 容器,就可以获取一个 Web 应用上下文
@WebAppConfiguration  
public class BaseTest extends Mockito{
    private static final ObjectMapper MAPPER = new ObjectMapper();
    protected Map<String,String> params = new HashMap<>();
    protected Map<String,String> headers = new HashMap<>();
    protected  MockMvc mockMvc;

    protected String prefix;

    /**
     * POST请求
     * @param url
     * @throws Exception
     */
    protected JsonResult 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));
            }
        }
        params.clear();
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders
                        .post(prefix + 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, JsonResult.class);
    }

    /**
     * GET请求
     * @param url url后缀
     * @return JsonResult
     * @throws Exception
     */
    protected JsonResult 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(prefix + 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, JsonResult.class);
    }

}

MockBaseTest.java

java 复制代码
@RunWith(MockitoJUnitRunner.class)
@ActiveProfiles("dev")
@PowerMockIgnore("javax.management.*")
public class MockBaseTest extends BaseTest{

}

示例:

java 复制代码
public class CustControllerTest extends MockBaseTest {

	@InjectMocks //用于创建一个实例,调用真实的方法
	private CustController custController;

	@Mock
	private CustService custService;

	@Before
	public void init(){
		this.prefix = "/api/cust";
		//MockitoAnnotations.initMocks(this);
		//初始化MVC
		this.mockMvc = MockMvcBuilders.standaloneSetup(custController).build();
		
    }
	@Test
	public void testInfoList() throws Exception{
		
		CustInfo custInfo = new CustInfo();
		custInfo.setIdNo("4304221955xxxxxxxx");
		when(custService.findCustInfo(anyLong())).thenReturn(custInfo);
        //添加请求参数
        params.put("id","1");
        //发送post请求
		JsonResult jsonResult = postHttp("/info");
		String idNo = (List<Map>)((Map)jsonResult.get("info")).get("idNo");
		Assert.assertNotNull(idNo);
		Assert.assertEquals(custInfo.getIdNo(),idNo);
	}

}
相关推荐
风霜不见闲沉月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·单元测试
程序猿小D7 天前
第三百零五节 Log4j教程 - Log4j日志记录方法
java·sql·junit·单元测试·log4j·mybatis·lucene
又菜又爱玩的晴晴7 天前
mockito+junit完成单元测试
junit·单元测试·mockito
板子小哥8 天前
LuatOS学习指南:开启物联网开发之旅
运维·服务器·开发语言·人工智能·物联网·junit·lua