简介
mock单词的意思为模拟,顾名思义,我们用它来进行单元测试,由于是单元测试,我们将用它模拟测试中所遇到的参数或者对象,保证测试为单元测试。
属性介绍
1、Verify
这个意思是验证单元测试的执行路径,以下是实例代码:
using mocks mockedList.add("one");
mockedList.add("two");
verify(mockedList).add("one");
//若调用成功,则程序正常运行,反之则会报告:
Wanted but not invoked:verify(mockedList).add("one");
错误。
2、 When().thenReturn()
这个意思是设置方法的返回值为特定值,验证预期返回是否和实际返回值所以一致。示例代码如下:
//stubbing using built-in anyInt() argument matcher
when(mockedList.get(anyInt())).thenReturn("element");
//stubbing using custom matcher (let's say isValid() returns your own matcher implementation):
when(mockedList.contains(argThat(isValid()))).thenReturn("element");
//following prints "element"
System.out.println(mockedList.get(999));
//you can also verify using an argument matcher
verify(mockedList).get(anyInt());
//argument matchers can also be written as Java 8 Lambdas
verify(mockedList).add(argThat(someString -> someString.length() > 5));
同样也有When().thenThrow(),这个的意思是指定返回时所抛异。
3、doThrow(), doAnswer(), doNothing(), doReturn() and doCallRealMethod()
一般和when配合使用,当条件满足是,执行对应的Answer的answer方法,如果answer方法抛出异常,那么测试不通过。doThrow同上。
示例代码:
doThrow(new RuntimeException()).when(mockedList).clear();
//following throws RuntimeException:
mockedList.clear();
其他用法同上
以上这些是最基本的函数使用和介绍。
推荐学习网站: