美文网首页
Mockito初识

Mockito初识

作者: 不知名的蛋挞 | 来源:发表于2019-08-22 13:52 被阅读0次

什么是Mockito

Mock是虚拟对象,是为了模拟真实对象而创建的,这些虚拟对象的行为是可控的。比如真实软件架构如下:

但测试软件架构如下:

Mockito可以完成哪些功能?

  • 验证Mock对象某函数是否执行,执行次数
  • Mock对象某函数有返回值,可以设置返回值。对于void的函数,可以设置抛出异常(即常说的安装桩)
  • 验证Mock对象函数执行顺序
  • 参数匹配(有很多内建的参数,也可以自己实现),这样使得验证函数交互或者设置返回值更加灵活
  • 可以捕获参数用于后续进一步验证或设置

Mockito常用API及使用方法

常用API

1. 创建Mock对象-创建Mock对象有两种方法

(1)使用mock函数

ILogService logService = mock(ILogService .class);

(2)使用@Mock注释

使用@Mock注释必须使用 @RunWith(MockitoJUnitRunner.class) 或 Mockito.initMocks(this) 进行mocks的初始化和注入

@Mock
ILogService logService;

@Before
public void setUp() throws Exception {
   MockitoAnnotations.initMocks(this);
}

但是创建mock对象不能对final,Anonymous ,primitive类进行mock。

2. 验证Mock对象函数是否执行、执行次数

public static <T> T verify(T mock,VerificationMode mode)

其中mode可以为times(x), atLeastOnce() 或者 never()。

verify(mock, times(5)).someMethod("was called five times");
verify(mock, atLeast(2)).someMethod("was called at least two times");
verify(mock, atLeastOnce()).someMethod(anyString());

3. 给模拟对象的有返回值的函数安装桩

when(methodCall).thenReturn() 或 when(methodCall).thenThrow()

4.给模拟对象返回void的函数安装桩

doThrow(new RuntimeException()).when(mockObject).methodCall();

5. 参数匹配

Mockito默认使用java的equals判断函数参数值,但有时为了更加灵活,可以使用参数匹配功能。

when(mockedObject.methodCall(anyInt())).thenReturn("element")
when(mockedObject.contains(argThat(isValid())).thenReturn("element"); //isValid()是自定义的参数匹配

使用示例

public class SimpleTest {
    @Test
    public void simpleTest1(){
        //创建mock对象,参数可以是类,也可以是接口
        List<string> mockedList = mock(List.class); 
        mockedList.add("three times");  
        mockedList.add("three times");  
        mockedList.add("three times");  
 
        //设置方法的预期返回值
        when(list.get(0)).thenReturn("helloworld");
        //设定返回异常
        when(list.get(1)).thenThrow(new RuntimeException("test excpetion"));

        String result = list.get(0);
 
        //验证方法调用(是否调用了get(0))
        verify(list).get(0);
        //验证是否调用了三次
        verify(mockedList, times(3)).add("three times");  
        //never()等同于time(0),一次也没有调用  
        verify(mockedList, times(0)).add("never happened");  
        verify(mockedList, never()).add("never happened");
       //atLeastOnece/atLeast()/atMost()  
        verify(mockedList, atLeastOnce()).add("three times");  
        verify(mockedList, atLeast(2)).add("twice");  
        verify(mockedList, atMost(5)).add("three times"); 
 
        //junit测试
        Assert.assertEquals("helloworld", result);
    }
}

相关文章

网友评论

      本文标题:Mockito初识

      本文链接:https://www.haomeiwen.com/subject/dxbxmftx.html