Junitmockito解耦合测试
Mock测试是单元测试的重要方法之一。
1、相关网址
官网:http://mockito.org/
2、什么是Mock测试
Mock测试就是在测试过程中,对于某些不容易构造(如HttpServletRequest必须在Servlet容器中才能构造出来)或者不容易获取比较复杂的对象(如JDBC中的ResultSet对象),用一个虚拟的对象(Mock对象)来创建以便测试的测试方法。
Mock最大的功能是帮你把单元测试的耦合分解开,如果你的代码对另一个类或者接口有依赖,它能够帮你模拟这些依赖,并帮你验证所调用的依赖的行为。
当我们需要测试A类的时候,如果没有Mock,则我们需要把整个依赖树都构建出来,而使用Mock的话就可以将结构分解开,像下面这样:
只需提供mockB和mockC的返回即可的,不需要知道其底层具体是怎么实现的。
3、mock使用的场景和好处
真实的对象具有不确定的行为,产生不可预测效果。(如:股票行情,天气预报),我们经常会遇到测试的时候需要去数据库中查询某些数据,但是未知的,就算是知道的,假如有一天数据被删除了或者被修改了,很难进行回归测试。
真实对象很难被创建的,真实对象的某些行为很难被触发。
真实对象实际上还不存在的。如:某个接口依赖其他系统的服务或者该接口还没开发出来。我们就可以使用mock假设其返回的数据进行测试。而不用等待其开发完接口,我们再进行测试。提高开发的效率
4、一些特点
可以mock具体类而不单止是接口
一点注解语法糖-@Mock
干净的验证错误是-点击堆栈跟踪,看看在测试中的失败验证;点击异常的原因来导航到代码中的实际互动。堆栈跟踪总是干干净净。
允许灵活有序的验证(例如:你任意有序verify,而不是每一个单独的交互)
支持“详细的用户号码的时间”以及“至少一次”验证
灵活的验证或使用参数匹配器的stub(anyObject(),anyString()或refEq()用于基于反射的相等匹配)
允许创建自定义的参数匹配器或者使用现有的hamcrest匹配器
5、maven配置
1)Junit的maven
复制代码
junit
junit
4.11
test
复制代码
2)mockito的maven
复制代码
org.mockito
mockito-all
1.9.5
test
复制代码
6、使用
首先我们需要引入静态资源
importstaticorg.mockito.Mockito.;
importstaticorg.junit.Assert.;
1)验证行为
复制代码
@Test
publicvoidverify_behaviour(){
//模拟创建一个List对象
Listmock=mock(List.class);
//使用mock的对象
mock.add(1);
mock.clear();//清空mock对象
//验证add(1)和clear()行为是否发生
verify(mock).add(1);
verify(mock).clear();
}
复制代码
2)模拟我们所期望的结果
复制代码
publicvoidwhen_thenReturn(){
//mock一个Iterator类
Iteratoriterator=mock(Iterator.class);
//预设当iterator调用next()时第一次返回hello,第n次都返回world
when(iterator.next()).thenReturn("hello").thenReturn("world");
//使用mock的对象
Stringresult=iterator.next()+""+iterator.next()+""+iterator.next();
//验证结果
assertEquals("helloworldworld",result);
}
复制代码
复制代码
@Test(expected=IOException.class)
publicvoidwhen_thenThrow()throwsIOException{
OutputStreamoutputStream=mock(OutputStream.class);
OutputStreamWriterwriter=newOutputStreamWriter(outputStream);
//预设当流关闭时抛出异常
doThrow(newIOException()).when(outputStream).close();
outputStream.close();
}
复制代码
3)参数匹配
复制代码
@Test
publicvoidwith_arguments(){
Comparablecomparable=mock(Comparable.class);
//预设根据不同的参数返回不同的结果
when(comparable.compareTo("Test")).thenReturn(1);
when(comparable.compareTo("Omg")).thenReturn(2);
assertEquals(1,comparable.compareTo("Test"));
assertEquals(2,comparable.compareTo("Omg"));
//对于没有预设的情况会返回默认值
assertEquals(0,comparable.compareTo("Notstub"));
}
复制代码
除了匹配制定参数外,还可以匹配自己想要的任意参数
复制代码
@Test
publicvoidwith_unspecified_arguments(){
Listlist=mock(List.class);
//匹配任意参数
when(list.get(anyInt())).thenReturn(1);
when(list.contains(argThat(newIsValid()))).thenReturn(true);
assertEquals(1,list.get(1));
assertEquals(1,list.get(999));
assertTrue(list.contains(1));
assertTrue(!list.contains(3));
}
privateclassIsValidextendsArgumentMatcher{
@Override
publicbooleanmatches(Objecto){
returno==1||o==2;
}
}
复制代码
需要注意的是如果你使用了参数匹配,那么所有的参数都必须通过matchers来匹配
复制代码
@Test
publicvoidall_arguments_provided_by_matchers(){
Comparatorcomparator=mock(Comparator.class);
Comparator.comparewww.baiyuewang.net("nihao","hello");
//如果你使用了参数匹配,那么所有的参数都必须通过matchers来匹配
verify(comparator).compare(anyString(),eq("hello"));
//下面的为无效的参数匹配使用
//verify(comparator).compare(anyString(),"hello");
}
复制代码
4)验证确切的调用次数
复制代码
@Test
publicvoidverifying_number_of_invocations(){
Listlist=mock(List.class);
list.add(1);
list.add(2);
list.add(2);
list.add(3);
list.add(3);
list.add(3);
//验证是否被调用一次,等效于下面的times(1)
verify(list).add(1);
verify(list,times(1)).add(1);
//验证是否被调用2次
verify(list,times(2)).add(2);
//验证是否被调用3次
verify(list,times(3)).add(3);
//验证是否从未被调用过
verify(list,never()).add(4);
//验证至少调用一次
verify(list,atLeastOnce()).add(1);
//验证至少调用2次
verify(list,atLeast(2)).add(2);
//验证至多调用3次
verify(list,atMost(3)).add(3);
复制代码
5)模拟方法体抛出异常
复制代码
@Test(expected=RuntimeException.class)
publicvoiddoThrow_when(){
Listlist=mock(List.class);
doThrow(newRuntimeException()).when(list).add(1);
list.add(1);
}
复制代码
6)验证执行顺序
复制代码
@Test
publicvoidverification_in_order(){
Listlist=mock(List.class);
Listlist2=mock(List.class);
list.add(1);
list2.add("hello");
list.add(2);
list2.add("world");
//将需要排序的mock对象放入InOrder
InOrderinOrder=inOrder(list,list2);
//下面的代码不能颠倒顺序,验证执行顺序
inOrder.verify(list).add(1);
inOrder.verify(list2).add("hello");
inOrder.verify(list).add(2);
inOrder.verify(list2).add("world");
}
复制代码
7)确保模拟对象上无互动发生
复制代码
@Test
publicvoidverify_interaction(){
Listlist=mock(List.class);
Listlist2=mock(List.class);
Listlist3=mock(List.class);
list.add(1);
verify(list).add(1);
verify(list,never()).add(2);
//验证零互动行为
verifyZeroInteractions(list2,list3);
}
复制代码
8)找出冗余的互动(即未被验证到的)
复制代码
@Test(expected=NoInteractionsWanted.class)
publicvoidfind_redundant_interaction(){
Listlist=mock(List.class);
list.add(1);
list.add(2);
verify(list,times(2)).add(anyInt());
//检查是否有未被验证的互动行为,因为add(1)和add(2)都会被上面的anyInt()验证到,所以下面的代码会通过
verifyNoMoreInteractions(list);
Listlist2=mock(List.class);
list2.add(1);
list2.add(2);
verify(list2).add(1);
//检查是否有未被验证的互动行为,因为add(2)没有被验证,所以下面的代码会失败抛出异常
verifyNoMoreInteractions(list2);
}
复制代码
9)使用注解的方式来快速模拟
在上面的测试中我们在每个测试方法里都mock了一个List对象,为了避免重复的mock,是测试类更具有可读性,我们可以使用下面的(@Mock)注解方式来快速模拟对象:
@Mock
privateListmockList;
我们再用注解的mock对象试试
@Test
publicvoidshorthand(){
mockList.add(1);
verify(mockList).add(1);
}
运行这个测试类你会发现报错了,mock的对象(mockList)为NULL,为此我们必须在基类中添加初始化mock的代码
复制代码
publicclassMockitoExample2{
@Mock
privateListmockList;
publicMockitoExample2(){
MockitoAnnotations.initMocks(this);
}
@Test
publicvoidshorthand(){
mockList.add(1);
verify(mockList).add(1);
}
}
复制代码
或者使用built-inrunner:MockitoJUnitRunner
复制代码
@RunWith(MockitoJUnitRunner.class)
publicclassMockitoExample2{
@Mock
privateListmockList;
@Test
publicvoidshorthand(){
mockList.add(1);
verify(mockList).add(1);
}
}
复制代码
更多的注解还有@Captor,@Spy,@InjectMocks
10)连续调用
复制代码
@Test(expected=RuntimeException.class)
publicvoidconsecutive_calls(){
//模拟连续调用返回期望值,如果分开,则只有最后一个有效
when(mockList.get(0)).thenReturn(0);
when(mockList.get(0)).thenReturn(1);
when(mockList.get(0)).thenReturn(2);
when(mockList.get(1)).thenReturn(0).thenReturn(1).thenThrow(newRuntimeException());
assertEquals(2,mockList.get(0));
assertEquals(2,mockList.get(0));
assertEquals(0,mockList.get(1));
assertEquals(1,mockList.get(1));
//第三次或更多调用都会抛出异常
mockList.get(1);
}
复制代码
11)使用回调生成期望值
复制代码
@Test
publicvoidanswer_with_callback(){
//使用Answer来生成我们我们期望的返回
when(mockList.get(anyInt())).thenAnswer(newAnswer |
|