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 对象

Mockito 链式调用


thenReturn、doReturn 等函数支持链式调用,用来指定函数特定调用次数时的行为。

示例1:

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

import static org.mockito.Mockito.*;

public class MockitoDemo {

    static class ExampleService {

        public int add(int a, int b) {
            return a+b;
        }

    }

    @Test
    public void test() {

        ExampleService exampleService = mock(ExampleService.class);

        // 让第1次调用返回 100,第2次调用返回 200
        when(exampleService.add(1, 2)).thenReturn(100).thenReturn(200);

        Assert.assertEquals(100, exampleService.add(1, 2));
        Assert.assertEquals(200, exampleService.add(1, 2));
        Assert.assertEquals(200, exampleService.add(1, 2));

    }

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

import static org.mockito.Mockito.*;

public class MockitoDemo {

    static class ExampleService {

        public int add(int a, int b) {
            return a+b;
        }

    }

    @Test
    public void test() {

        ExampleService exampleService = mock(ExampleService.class);

        // 让第1次调用返回 100,第2次调用返回 200
        doReturn(100).doReturn(200).when(exampleService).add(1, 2);

        Assert.assertEquals(100, exampleService.add(1, 2));
        Assert.assertEquals(200, exampleService.add(1, 2));
        Assert.assertEquals(200, exampleService.add(1, 2));

    }

}

( 本文完 )

文章目录