请参考下面有关于打标的代码。java
//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。git
打标(Stubbing)能够被重写:例如一个通用的打标能够在启动的时候被肯定(fixture),可是测试方法能够对其进行重写(override)。请注意重写的打标可能会在有不少标记的时候存在潜在的问题。github
一旦被打标,方法将会老是返回已标记的内容,这个与这个方法被调用多少次无关。api
最后的标记很是重要——当你对有相同参数的方法进行屡次标记的时候。换句话说就是:标记的顺序是有关的(the order of stubbing matters),可是这个意义并非很大。例如,这个只在标记彻底相同的方法或者有时候参数匹配(argument matchers)被启用的时候,等状况下才会出现。, etc.app
测试代码请访问 GitHubide
请注意,上面的测试代码在运行的时候回出现错误。测试
这是由于在测试代码运行的时候,咱们尝试输出 mockedList.get(1),这个在测试的时候,由于咱们打标为抛出异常,因此这一句话将会在测试代码中抛出异常。spa
运行时候,抛出异常的界面以下:code