Here is another great use case for Answer: You can pass an Answer instance as second parameter to the mock method to define the default answer for all invocations on the returned mock object, which have not been stubbed.
Example: Suppose you want a pseudo object (a mock object, which throws an AssertionError whenever an unstubbed/unexpected method is called -- see "xUnit Test Patterns" by Gerard Meszaros) To easily construct a pseudo object you can use the following method:
public static T pseudo(Class clazz) { return mock(clazz, new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { throw new AssertionError("Unexpected method call " + invocationOnMock); } }); }
Now you can write
Foo foo = pseudo(Foo.class);
in your test class to create a pseudo object of type Foo.
The only draw back here is, that you can not use the common stubbing style:
when(foo.method(...)).thenXxx(...);
because that leads to an AssertionError. To stub methods you need to write:
Here is another great use case for Answer: You can pass an Answer instance as second parameter to the mock method to define the default answer for all invocations on the returned mock object, which have not been stubbed.
ReplyDeleteExample: Suppose you want a pseudo object (a mock object, which throws an AssertionError whenever an unstubbed/unexpected method is called -- see "xUnit Test Patterns" by Gerard Meszaros) To easily construct a pseudo object you can use the following method:
public static T pseudo(Class clazz) {
return mock(clazz, new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
throw new AssertionError("Unexpected method call " + invocationOnMock);
}
});
}
Now you can write
Foo foo = pseudo(Foo.class);
in your test class to create a pseudo object of type Foo.
The only draw back here is, that you can not use the common stubbing style:
when(foo.method(...)).thenXxx(...);
because that leads to an AssertionError. To stub methods you need to write:
doXxx(...).when(foo).method(...);
@Unknown wouldn't that be the same as Mockito.verifyNoMoreInteractions(foo) ?
ReplyDelete