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

后端 未结 3 2122
广开言路
广开言路 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 20:57

    It's counting your setup as invocations since deeps stubs is not supported in the verification API, and complains on the second call which is:

    when(mockSandBox.getSand().doB()).thenReturn(1);
    

    I would skip using RETURNS_DEEP_STUBS and just use another mock:

    ...
    @Mock
    SandBox mockSandBox;
    
    @Mock
    Sand sand;
    
    @Test
    public void should(){
        when(mockSandBox.getSand()).thenReturn(sand);
        when(sand.doA()).thenReturn(1);
        when(sand.doB()).thenReturn(1);
        when(sand.doC()).thenReturn(1);
    ...
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-18 21:13

    From documention: " Verification API does not support 'chaining' so deep stub doesn't change how you do verification."

    Source: http://mockito.googlecode.com/svn/tags/1.8.3/javadoc/org/mockito/Mockito.html#RETURNS_DEEP_STUBS

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