Mockito 指南

Mockito 是一个模拟测试框架,主要功能是在单元测试中模拟类/对象的行为。

👉 所有文章
入门 引入依赖包 使用 mock 方法模拟类和接口 使用 @Mock 注解 mock 泛型类、泛型接口 参数匹配 参数匹配顺序 spy 和 @Spy 注解 @InjectMocks 注解注入 mock 对象 使用 thenReturn 设置方法的返回值 使用 thenThrow 让方法抛出异常 使用then、thenAnswer 自定义方法处理逻辑 使用 doReturn 设置方法的返回值 使用 doThrow 让方法抛出异常 使用 doAnswer 自定义方法处理逻辑 使用 doNothing 让 void 函数什么都不做 使用 MockitoJUnitRunner 运行 JUnit 测试 使用 MockitoAnnotations.initMocks 让 @Mock 等注解生效 使用 reset 重置对象 使用 thenCallRealMethod 调用 spy 对象的真实方法 使用 verify 校验是否发生过某些操作 使用 mockingDetails 判断对象是否为 mock对象、spy 对象 链式调用 测试隔离 使用 PowerMock 让 Mockito 支持静态方法 临时 mock 对象

Mocktio 使用 mock 方法模拟类和接口


org.mockito.Mockito 的 mock 方法可以模拟类和接口。

mock 类:

import org.junit.Assert;
import org.junit.Test;
import java.util.Random;

import static org.mockito.Mockito.*;

public class MockitoDemo {

    @Test
    public void test() {
        Random mockRandom = mock(Random.class);
        when(mockRandom.nextInt()).thenReturn(100);  // 指定调用 nextInt 方法时,永远返回 100

        Assert.assertEquals(100, mockRandom.nextInt());
        Assert.assertEquals(100, mockRandom.nextInt());
    }
}

注意,mock 对象的方法的返回值默认都是返回类型的默认值。例如,返回类型是 int,默认返回值是 0;返回类型是一个类,默认返回值是 null。

import org.junit.Assert;
import org.junit.Test;
import java.util.Random;

import static org.mockito.Mockito.*;

public class MockitoDemo {

    @Test
    public void test() {
        Random mockRandom = mock(Random.class);

        System.out.println( mockRandom.nextBoolean() );
        System.out.println( mockRandom.nextInt() );
        System.out.println( mockRandom.nextDouble() );
    }
}

运行 test 方法,输出:

false
0
0.0

mock 接口:

import org.junit.Assert;
import org.junit.Test;

import java.util.List;

import static org.mockito.Mockito.*;

public class MockitoDemo {


    @Test
    public void test() {
        List mockList = mock(List.class);

        Assert.assertEquals(0, mockList.size());
        Assert.assertEquals(null, mockList.get(0));

        mockList.add("a");  // 调用 mock 对象的写方法,是没有效果的

        Assert.assertEquals(0, mockList.size());      // 没有指定 size() 方法返回值,这里结果是默认值
        Assert.assertEquals(null, mockList.get(0));   // 没有指定 get(0) 返回值,这里结果是默认值

        when(mockList.get(0)).thenReturn("a");          // 指定 get(0)时返回 a

        Assert.assertEquals(0, mockList.size());        // 没有指定 size() 方法返回值,这里结果是默认值
        Assert.assertEquals("a", mockList.get(0));      // 因为上面指定了 get(0) 返回 a,所以这里会返回 a

        Assert.assertEquals(null, mockList.get(1));     // 没有指定 get(1) 返回值,这里结果是默认值
    }
}

( 本文完 )

文章目录