Correct usage of strict stubbings -> PotentialStubbingProblem: Strict stubbing argument mismatch

4,053 views
Skip to first unread message

Alexander Jones

unread,
Oct 12, 2018, 10:07:59 AM10/12/18
to mockito
Hi all,

I had some questions regarding use cases of new "Strict" stubbing.

With Junit5 & @ExtendWith(MockitoExtension.class) I've noticed that it errors out when I think it shouldn't (when compared with Junit4 & @RunWith(MockitoJUnitRunner.class) )
I have a very simple test case, which I consider to be both good code, and good mocking. Which gets highlighted as incorrect stubbing usage under Strict (default) checking

@Mock
private Map<String, Object> mockMap;
@Mock
private Object mockObject;

@Test
void testShouldReturnObjectsFromAMap() {
    // When
    when(mockMap.get("A")).thenReturn("Apple");
    when(mockMap.get("B")).thenReturn(mockObject);

    // Then
    assertThat(mockMap.get("A")).isEqualTo("Apple");
    assertThat(mockMap.get("B")).isEqualTo(mockObject);
}

The above generates the org.mockito.exceptions.misusing.PotentialStubbingProblem error.
This is a very common example of code in my company (which runs fine under the Junit4 runner)

What should I do with this? (I'd rather not D as we like Stricts' warnings normally!):
    A) that's terrible code, why would you write that
    B) that's not how you use Mockito
    C) oh, that's something we overlooked, and will allow that in the next Mockito release
    D) use Lenient().when().thenReturn();
    E) something else

As it's my first post, and I don't want to appear like I've come in bashing. I'd like to add, I love Mockito, and we use it everywhere. Really appreciate the work you guys do

Alexander Jones

unread,
Oct 12, 2018, 11:00:09 AM10/12/18
to mockito
To further add, I have just seen : https://stackoverflow.com/questions/52139619/simulation-of-service-using-mockito-2-leads-to-stubbing-error
Which is the only other topic I can find on this. I'm hoping the solution to the above is not:

// From this

when(mockMap.get("A")).thenReturn("Apple");
when(mockMap.get("B")).thenReturn(mockObject);

// To this
when(mockMap.get(anyString())).thenAnswer(invocation -> {
    Object arg = invocation.getArgument(0);
    if ("A".equals(arg)) return "Apple";
    if ("B".equals(arg)) return system;
});

I'm hoping there is a better way.
That said: I only dislike the above because it is so verbose. If there were shorter (and clearer) method to do the same thing, I'd be less averse to the solution


Christian Schwarz

unread,
Oct 22, 2018, 9:51:32 AM10/22/18
to mockito
Hi Alexander,

it looks like a bug! You should file a ticket at github with a short, self contained, compilable example.

Reply all
Reply to author
Forward
0 new messages