@Beta public final class CallsRealOrExceptionAnswer extends Object implements org.mockito.stubbing.Answer<Object>, Serializable
UnstubbedMethodException
, like the
ThrowsMethodExceptionAnswer
.
This can be useful to create light-weight Fake Doubles (in particular some with state). For example:
import static ...testutils.mockito.MoreAnswers.realOrException; interface Service { List<Thing> getThings(); boolean installThing(Thing thing); } abstract class FakeService implements Service { // Ignore getThings() - we don't need that for this test boolean installThing(Thing thing) { LOGGER.log("not really installed"); return false; } } Service fake = Mockito.mock(FakeService.class, realOrException())
TIP: An impact of Mockito is that, just like in standard Mockito, constructors (and thus field initializers) are not called. So in your abstract fake class, instead of:
abstract class FakeService implements Service { private final List<Thing> things = new ArrayList<>(); public List<Thing> getThings() { return things; } @Override public boolean installThing(Thing thing) { return things.add(thing); } }
you'll just need to do:
abstract class FakeService implements Service { private List<Thing> things; public List<Thing> getThings() { if (things == null) things = new ArrayList<>() return things; } @Override public boolean installThing(Thing thing) { return getThings().add(thing); } }
The big advantage of Mikitos versus just writing classes implementing service interfaces without using Mockito at all is that you don't have to implement a lot of methods you don't care about - you can just make an abstract fake class (incl. e.g. an inner class in your Test) and implement only one or some methods. This keeps code shorter and thus more readable.
The advantage of Mikitos VS pure Mockito's when/thenAnswer are that they:
Mockito.mock(Class, Answer)
,
ThrowsMethodExceptionAnswer
,
Mockito.CALLS_REAL_METHODS
,
Mockito.CALLS_REAL_METHODS
,
Serialized FormModifier and Type | Method and Description |
---|---|
Object |
answer(org.mockito.invocation.InvocationOnMock invocation) |
Copyright © 2019 OpenDaylight. All rights reserved.