The UnnecessaryStubbingException
occurs when you try to stub a method but it's not actually used in the code being tested. This usually happens when there are multiple stubs for the same method, and Mockito detects that some of them are unnecessary.
In your case, the exception might be caused by the fact that you have not used the mocked method in your test code, so Mockito detects it and throws the exception.
To avoid this, you need to make sure that the method you are mocking is actually used in your test code.
For example the next code will work without any problems:
@Test
public void unnecessaryStubbings() {
final MyService myServiceMock = Mockito.mock(MyService.class);
when(myServiceMock.mymethod("aaa", myEnum.ONE)).thenReturn(true);
when(myServiceMock.mymethod("bbb", myEnum.ONE)).thenReturn(false);
Assertions.assertTrue(myServiceMock.mymethod("aaa", myEnum.ONE));
Assertions.assertFalse(myServiceMock.mymethod("bbb", myEnum.ONE));
}
where in the next case the UnnecessaryStubbingException
will be thrown:
@Test
public void unnecessaryStubbings() {
final MyService myServiceMock = Mockito.mock(MyService.class);
when(myServiceMock.mymethod("aaa", myEnum.ONE)).thenReturn(true);
when(myServiceMock.mymethod("bbb", myEnum.ONE)).thenReturn(false); // Unnecessary Stabbing
Assertions.assertTrue(myServiceMock.mymethod("aaa", myEnum.ONE));
// Assertions.assertFalse(myServiceMock.mymethod("bbb", myEnum.ONE));
}
You can also read more about that exception and how to handle it in that thread.