How to resolve Unneccessary Stubbing exception

前端 未结 13 1357
无人共我
无人共我 2020-12-24 03:57

My Code is as below,

@RunWith(MockitoJUnitRunner.class)
public class MyClass {

    private static final String code =\"Test\";

    @Mock
     private MyCl         


        
相关标签:
13条回答
  • 2020-12-24 04:35

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-24 04:38

    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 ;)

    0 讨论(0)
  • 2020-12-24 04:38
     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?

    0 讨论(0)
  • 2020-12-24 04:38

    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();
    
    0 讨论(0)
  • Replace @RunWith(MockitoJUnitRunner.class) with @RunWith(MockitoJUnitRunner.Silent.class).

    0 讨论(0)
  • 2020-12-24 04:42

    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).

    0 讨论(0)
提交回复
热议问题