When overriding a stub, the original stub should not be invoked
See original GitHub issueSituation: I have a test class in which a mock should invoke a custom Answer during most test methods, but a couple test methods need different behavior. So I created a Before method to stub the mocks, then in the relevant test methods, I stub them again to override. The problem is that Mockito invokes the original Answer when I stub the mock the second time, which in my case causes a NPE because the custom Answer is doing things with the invocation parameters.
I’m working around the problem by creating an OverridableAnswer that gets attached to the mock, and delegates to the real Answer. But this creates a bunch of unnecessary boilerplate. It would be nice if Mockito noticed that the stubbed method is being invoked during a new stubbing, and skip calling the originally stubbed Answer.
This issue was discovered on Mockito 1.10.19 (we currently can’t upgrade to 2.x because PowerMock’s support for Mockito 2 is broken), but I confirmed it still exists in 2.2.22.
Here’s a simple reproducer:
@Test
public void testOverrideStub() {
A instance = Mockito.mock(A.class);
Mockito.when(instance.foo()).then(new Answer<Integer>() {
public Integer answer(InvocationOnMock invocation) throws Throwable {
invoked = true;
return 1;
}
});
Mockito.when(instance.foo()).then(new Answer<Integer>() {
public Integer answer(InvocationOnMock invocation) throws Throwable {
return 2;
}
});
Assert.assertFalse("Overriding stubbing should not invoke original stub", invoked);
}
private static class A {
public int foo() {return 0;}
}
Issue Analytics
- State:
- Created 7 years ago
- Comments:8 (4 by maintainers)
Top GitHub Comments
Sorry to comment on this closed issue. But I can’t seem to grok this. I have simple test class which defines a
@Before
method. Therein I mock a certain call. This mock is good for all but two of my@Test
s. That looks something like this:In the two deviates I overwrite (or so I thought) the stub like so:
This fails.
someMethod
is still only called once (I expected twice, once for each item in the list). Am I mixingdoReturn
andwhen
wrong?You can use:
as a workaround. Method
foo()
is executed on the proxy, so the original stubbing shouldn’t be called on the second stubbing. This syntax in general should be rather used for spies and void methods as it doesn’t provide compile time type checking.