Mockito: Verify Mock (with “RETURNS_DEEP_STUBS”) Returns More Calls Than Expected

后端 未结 3 2113
广开言路
广开言路 2021-02-18 20:22

Looking at the code below, I only expect the call to getSand() to happen once, but the test is failing with four calls to it. Where are these calls happening? I wan

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-18 21:08

    From the documentation of Answers.RETURNS_DEEP_STUBS:

    Please see the {@link org.mockito.Mockito#RETURNS_DEEP_STUBS} documentation for more details.
    

    From Mockito.RETURNS_DEEP_STUBS:

    Verification only works with the last mock in the chain. You can use verification modes. 
    [...]
    when(person.getAddress(anyString()).getStreet().getName()).thenReturn("deep");
    [...]
    inOrder.verify(person.getAddress("the docks").getStreet(), times(1)).getName();
    

    So, I think, in order to get your verifies to work, you have to rewrite your Mocks to something like this:

    @Mock
    SandBox mockSandBox;
    
    @Mock
    Sand mockSand;
    
    @Test
    public void should()
    {
        when( mockSand.doA() ).thenReturn( 1 );
        when( mockSand.doB() ).thenReturn( 1 );
        when( mockSand.doC() ).thenReturn( 1 );
    
        when( mockSandBox.getSand() ).thenReturn( mockSand );
    
        DeepSand deepSand = new DeepSand( mockSandBox );
        deepSand.getTipple();
    
        verify( mockSandBox, times( 1 ) ).getSand();
    }
    

    Or only verify the invocations of doA, doB and doC and not verify the invocation of getSand(). - Which depends on what exactly you want to test for here.

提交回复
热议问题