4

I have some testing method:

@Test public void test_method() { MyObj mock = mock(MyObj.class); when(mock.get("testName", "1")).thenReturn("Result1"); when(mock.get("test", "2")).thenReturn("rrrr"); } 

when I trying run this method I had exception:

org.mockito.exceptions.misusing.PotentialStubbingProblem: Strict stubbing argument mismatch. Please check: Typically, stubbing argument mismatch indicates user mistake when writing tests. Mockito fails early so that you can debug potential problem easily. However, there are legit scenarios when this exception generates false negative signal: - stubbing the same method multiple times using 'given().will()' or 'when().then()' API Please use 'will().given()' or 'doReturn().when()' API for stubbing. - stubbed method is intentionally invoked with different arguments by code under test Please use default or 'silent' JUnit Rule (equivalent of Strictness.LENIENT). For more information see javadoc for PotentialStubbingProblem class. 

How can I mock this method?

2
  • 1
    In your test you do not do anything with the class under test, hence the mocks are not used. Please add a minimal reproducible example. Commented Sep 17, 2019 at 13:33
  • Check this out: we can't read minds. Include the class definition of the MyObj class. Commented Sep 17, 2019 at 13:49

3 Answers 3

3

The error message tells you:

stubbing the same method multiple times using 'given().will()' or 'when().then()' API Please use 'will().given()' or 'doReturn().when()' API for stubbing.

Sign up to request clarification or add additional context in comments.

2 Comments

That error message refers to the case when(foo.get("1")).thenReturn(true);when(foo.get("1")).thenReturn(false) that should be written as doReturn(true,false).when(foo).get("1"); (at least I suppose)
'will().given()' or 'doReturn().when()' produces the same error
1

You can use any() to mock one method with different parameters. any() will be used as a dynamic variable.

e.g doReturn(order).when(orderRepository).save(any(Order.class));

I was saving orderRepository with 2 different Order parameters so I have used any with Order class.

Comments

1

For me worked add the annotation @MockitoSettings(strictness = Strictness.LENIENT)

@ExtendWith(MockitoExtension::class) @MockitoSettings(strictness = Strictness.LENIENT) 

1 Comment

Need to be careful with this as you may risk to have just a useless test, hiding potential issues.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.