My Code is as below,
@RunWith(MockitoJUnitRunner.class)
public class MyClass {
private static final String code =\"Test\";
@Mock
private MyCl
I had UnnecessaryStubbingException
when I tried to use the when
methods on a Spy object.
Mockito.lenient()
silenced the exception but the test results were not correct.
In case of Spy objects, one has to call the methods directly.
@ExtendWith(MockitoExtension.class)
@RunWith(JUnitPlatform.class)
class ArithmTest {
@Spy
private Arithm arithm;
@Test
void testAddition() {
int res = arithm.add(2, 5);
// doReturn(7).when(arithm).add(2, 5);
assertEquals(res, 7);
}
}
For me neither the @Rule
nor the @RunWith(MockitoJUnitRunner.Silent.class)
suggestions worked. It was a legacy project where we upgraded to mockito-core 2.23.0.
We could get rid of the UnnecessaryStubbingException
by using:
Mockito.lenient().when(mockedService.getUserById(any())).thenReturn(new User());
instead of:
when(mockedService.getUserById(any())).thenReturn(new User());
Needless to say that you should rather look at the test code, but we needed to get the stuff compiled and the tests running first of all ;)
when(dao.doSearch(dto)).thenReturn(inspectionsSummaryList);//got error in this line
verify(dao).doSearchInspections(dto);
The when
here configures your mock to do something. However, you donot use this mock in any way anymore after this line (apart from doing a verify
). Mockito warns you that the when
line therefore is pointless. Perhaps you made a logic error?
If you're using this style instead:
@Rule
public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);
replace it with:
@Rule
public MockitoRule rule = MockitoJUnit.rule().silent();
Replace @RunWith(MockitoJUnitRunner.class)
with @RunWith(MockitoJUnitRunner.Silent.class)
.
Replace
@RunWith(MockitoJUnitRunner.class)
with
@RunWith(MockitoJUnitRunner.Silent.class)
or remove @RunWith(MockitoJUnitRunner.class)
or just comment out the unwanted mocking calls (shown as unauthorised stubbing).