首页 > 其他 > 详细

Mockito 2 关于打标(stubbing)

时间:2019-09-18 12:01:37      阅读:89      评论:0      收藏:0      [点我收藏+]

请参考下面有关于打标的代码。

//You can mock concrete classes, not just interfaces
LinkedList mockedList = mock(LinkedList.class);
 
//stubbing
when(mockedList.get(0)).thenReturn("first");
when(mockedList.get(1)).thenThrow(new RuntimeException());
 
//following prints "first"
System.out.println(mockedList.get(0));
 
//following throws runtime exception
System.out.println(mockedList.get(1));
 
//following prints "null" because get(999) was not stubbed
System.out.println(mockedList.get(999));
 
//Although it is possible to verify a stubbed invocation, usually it‘s just redundant
//If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).
//If your code doesn‘t care what get(0) returns, then it should not be stubbed.
verify(mockedList).get(0);
  • 在默认情况下,所有的方法都会有一个返回值。mock 函数默认返回的是 null,一个空的集合或者一个被对象类型包装的内置类型。例如,针对 int/Integer 将会返回 0,针对 boolean/Boolean 将会返回 false。
  • 打标(Stubbing)可以被重写:例如一个通用的打标可以在启动的时候被确定(fixture),但是测试方法可以对其进行重写(override)。请注意重写的打标可能会在有很多标记的时候存在潜在的问题。
  • 一旦被打标,方法将会总是返回已标记的内容,这个与这个方法被调用多少次无关。
  • 最后的标记非常重要——当你对有相同参数的方法进行多次标记的时候。换句话说就是:标记的顺序是有关的(the order of stubbing matters),但是这个意义并不是很大。例如,这个只在标记完全相同的方法或者有时候参数匹配(argument matchers)被启用的时候,等情况下才会出现。, etc.

请注意,上面的测试代码在运行的时候回出现错误。

这是因为在测试代码运行的时候,我们尝试输出 mockedList.get(1),这个在测试的时候,因为我们打标为抛出异常,所以这一句话将会在测试代码中抛出异常。

运行时候,抛出异常的界面如下:

技术分享图片

 

https://www.cwiki.us/pages/viewpage.action?pageId=47843418

Mockito 2 关于打标(stubbing)

原文:https://www.cnblogs.com/huyuchengus/p/11540692.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!