简体   繁体   中英

Mockito verify still fails on using all Matchers

I am recently writing a JUnit test and I acknowledged that Mockito either needs all Raw values or using all Matchers but I find the following case still fails with all Matchers, error message is:

Invalid use of argument matchers, 0 matchers expected: 1 recorded:

I tested a little bit and it looks like something to do with using a stub method as value for the eq() Matcher. See example below:

I have a Class A very simple

public class A {

    public void testMockitoMatcher(double a, String b){

    }
}

Here is my test case

import org.junit.Test;

import static org.mockito.Mockito.*;

public class SomeUnitTest {
    private A mockA = mock(A.class);

    @Test
    public void allMatchersDoesntWork() {
        Object mockObject = mock(Object.class);
        String someString = "Just some mocked String value to return";
        when(mockObject.toString()).thenReturn(someString);

        mockA.testMockitoMatcher(1312d, mockObject.toString());

        verify(mockA, times(1)).testMockitoMatcher(anyDouble(), eq(someString));    //<- This works
        verify(mockA, times(1)).testMockitoMatcher(anyDouble(), eq(mockObject.toString()));    //<- This doesn't by using stub method toString() to return the String value as param to eq()
    }
}

I also verified by using debug at 2nd verify statement that mockObject.toString() can still return the stubbed value for me. Also both verify use all Matchers, why mockito still gives me only 1 Matchers recorded instead of 2 at the 2nd verify?

Thanks!

Mockito expects your tests to be in three stages.

  • You set things up for the test, including stubbing any methods that need to be stubbed (the "arrange" stage).
  • You run the actual method that you're trying to test (the "act" stage).
  • You make assertions about the output of the test, possibly including verifying which methods got called on your mocks (the "assert" stage).

You need to do these three things, in this sequence, because Mockito tracks whether you're stubbing, verifying or whatever. It also has its own internal stack which stores Matchers, for use in stubbing or verification.

In your second verify call in your example, the call to anyDouble() puts the Matcher onto the stack. But this creates an invalid state for the call to mockObject.toString() .

Don't do this. Once you're ready to run your assertions and verifications, you shouldn't be making any more calls to stubbed methods. Keep the "arrange", "act" and "assert" stages of each test entirely separate from each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM