Mockito单元测试保姆级实战(一个java Mock测试框架)

Posted 栗子~~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mockito单元测试保姆级实战(一个java Mock测试框架)相关的知识,希望对你有一定的参考价值。

文章目录

前言

  如果您觉得有用的话,记得给博主点个赞,评论,收藏一键三连啊,写作不易啊^ _ ^。
  而且听说点赞的人每天的运气都不会太差,实在白嫖的话,那欢迎常来啊!!!


Mockito单元测试保姆级实战

01 Mockito相关

01::01 前期准备

import org.mockito.InjectMocks;
import org.mockito.Mock;
@InjectMocks
ServiceTest serviceTest;
@Mock
ServiceTestMapper mapper;

@Mock:模拟出一个Mock对象,对象是空的,需要指明对象调用什么方法,传入什么参数时,返回什么值
@InjectMocks:依赖@Mock对象的类,也即是被测试的类。@Mock出的对象会被注入到@InjectMocks对象中

01::02 单元测试注解

@RunWith(PowerMockRunner.class)
@PrepareForTest()
@PowerMockIgnore("javax.net.ssl.*","javax.management.*")

01::03 为UT提供框架使用的自动验证

import org.mockito.MockitoAnnotations;
MockitoAnnotations.initMocks(this);

01::04 给测试类中的变量赋值

import org.springframework.test.util.ReflectionTestUtils;
ReflectionTestUtils.setField(serviceTest,"变量名","要赋给该变量的值");

01::05 给测试类中的方法设置返回值

import org.powermock.api.mockito.PowerMockito;
import static org.mockito.ArgumentMatchers.any;
PowerMockito.when(mapper.test(any(String.class))).thenReturn(返回内容)

01::06 给测试类中的方法抛出异常

import org.powermock.api.mockito.PowerMockito;
import static org.mockito.ArgumentMatchers.any;
PowerMockito.when(mapper.test(any(String.class))).thenThrow(new 异常);

01::07 给测试类中的方法设置不返回对象

import org.powermock.api.mockito.PowerMockito;
import static org.mockito.ArgumentMatchers.any;
PowerMockito.doNothing().when(serviceTest).mapper.test(any(String.class));

01::08 Mock方法内部new出来的对象

例子:
File file = new File(path);
file.exists();
单元测试:
File file1 = PowerMockito.mock(File.class);
PowerMockito.whenNew(File.class).withArguments(file).thenReturn(file1);
PowerMockito.when(file1.exists()).thenReturn(true);

01::09 给测试类中的静态类调静态方法提供返回值

测试类头部:
@PrepareForTest(静态类.class)
前期准备:
@Before
public void init()
PowerMockito.mockStatic(静态类.class);

调用:
PowerMockito.when(静态类.静态方法()).thenReturn(返回内容);

02 辅助Mockito

02 ::01 junit常用注解

junit常用注解
@Test(timeout = 10)
测试,该注解必须加到方法上
timeout超时时间,单位是毫秒
终止死循环,当达到设定的值,结束循环
@Ignore
忽略不想被测试的方法,该注解必须加到方法上,也可以加到类上(慎用)
@RunWith(SpringJUnit4ClassRunner.class)
把junit和spring整合到一块,该注解加到类上
@ContextConfiguration(locations = “classpath:conf/applicationContext.xml”)
用于加载spring配置文件的注解,添加到类上
locations代表spring配置文件路径的数组,数组的类型为Stirng
classpath:这个东西代表从源包下开始寻找
@Resource(name = “blogService”)
注入属性的注解,就相当于set、get方法,name指明bean的id值
@Before
在所有方法之前执行,一般加到方法上
@After
在所有方法之后执行,一般加到方法上
@Transactional
@TransactionConfiguration(transactionManager = “transactionManager”, defaultRollback = true)
上边这俩注解要一块用,用于事物控制,加到类上
transactionManager代表配置文件中事务管理器bean的id值
defaultRollback代表事物回滚,默认值为true,是回滚的

02:02 assert常用方法

Assert.assertEquals(“message”,A,B):
判断对象AB是否相等,这个判断比较时调用了equals()方法。
Assert.assertSame(“message”,A,B):
判断对象AB是否相同,使用的是==操作符。
Assert.assertTure(“message”,A):
判断A条件是否为真。
Assert.assertFalse(“message”,A):
判断A条件是否不为真。
Assert.assertNotNull(“message”,A):
判断A对象是否不为null
Assert.assertArrayEquals(“message”,A,B):
判断A数组与B数组是否相等。
等等.............................................

03 实战测试

03::01 要单元测试的实例


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

public class HttpUtil 
    private   String url = "";
    /**
     * @param param 传参
     * @param heads 自定义请求头
     * */
    public String httpPost(String param, Map<String,String> heads)  
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(60000).setConnectTimeout(60000)
                .setConnectionRequestTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type","application/json;charset=UTF-8");
        if (heads != null)
            heads.forEach((k,v) -> httpPost.setHeader(k,v));
        
        CloseableHttpClient httpClient = null;
        httpPost.setEntity(new StringEntity(param,"UTF-8"));
        httpClient = HttpClients.custom().disableAutomaticRetries().build();

        String result = null;
        try
            CloseableHttpResponse execute = httpClient.execute(httpPost);
            HttpResponse response = execute;
            HttpEntity entity = response.getEntity();
            result  = EntityUtils.toString(entity,"UTF-8");
        catch (IOException e)
            e.printStackTrace();
            return null;
        
        return result;
    


03::02 单元测试的实例


import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;

import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.test.util.ReflectionTestUtils;

import java.io.IOException;

import static org.mockito.ArgumentMatchers.any;
/**
 * 单元测试
 * author : yangzhenyu
 * **/
@RunWith(PowerMockRunner.class)
@PrepareForTest(HttpClientBuilder.class, EntityUtils.class)
@PowerMockIgnore("javax.net.ssl.*","javax.management.*")
public class HttpUtilTest 
    @InjectMocks
    private HttpUtil httpUtil;

    @Mock
    CloseableHttpClient httpClient;
    @Mock
    CloseableHttpResponse response;

    @Mock
    HttpEntity entity;
    @Mock
    HttpClientBuilder httpClientBuilder;

    @Before
    public void init()
        PowerMockito.mockStatic(HttpClientBuilder.class);
        PowerMockito.mockStatic(EntityUtils.class);

    
    /**
     * http post 测试方案1.0
     * given 准备测试数据 data
     * when  返回正确的格式
     * input param 传参,heads 自定义请求头
     * then 等值判断
     *
     * */
    @Test
    public void test_HttpUtil_1_0() throws IOException 
        //given
        String data = "\\"II\\":\\"2\\"";
        //when
        ReflectionTestUtils.setField(httpUtil,"url","http://127.0.0.1:8080");

        PowerMockito.when(HttpClients.custom()).thenReturn(httpClientBuilder);
        PowerMockito.when(httpClientBuilder.disableAutomaticRetries()).thenReturn(httpClientBuilder);
        PowerMockito.when(httpClientBuilder.build()).thenReturn(httpClient);

        PowerMockito.when(httpClient.execute(any(HttpPost.class))).thenReturn(response);
        PowerMockito.when(response.getEntity()).thenReturn(entity);
        PowerMockito.when(EntityUtils.toString(entity,"UTF-8")).thenReturn("0rsgfe223323");
        String s = httpUtil.httpPost(data, null);
        //then
        Assert.assertEquals("0rsgfe223323",s);
    


以上是关于Mockito单元测试保姆级实战(一个java Mock测试框架)的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot 单元测试,保姆级教程!

Junit单元测试保姆级教程

PowerMock单元测试

Mockito一个采用Java编写用于单元测试的Mocking框架

[单元测试]Java单元测试,基于Mockito的第一次尝试

Python应用实战案例-pyspark库从安装到实战保姆级讲解