NPE in Mockito argument matcher with doReturn causing all other tests to fail

270 Views Asked by At

I am using TestNG along with Mockito for my test classes. I tried to create a spy object and used ArgumentMatchers to stub a method call. While using argument matchers, Mockito states that to match a primitive type we need to use anyLong(),anyInt(),anyChar() or something similar depending on the required argument type. So in this case if we use any() then it would cause a NullPointerException.

I tried three methods:

  1. NPE would be thrown because I used any() to match a primitive argument
  2. NPE would be thrown because I used throw new NullPointerException()
  3. No exceptions thrown.

The below is the code I have used. (I have used static imports for Mockito methods)

@Test
public class MyTest {
    class Something {
        public int someMethod(long someLong, int someInt, Set<Long> someSet) {
            return 1;
        }
    }

    @Test
    public void testOne() {
        Something s = spy(new Something());
        doReturn(5).when(s).someMethod(any(), any(), any()); // NPE
    }

    @Test
    public void testTwo(){
        Something s = spy(new Something());
        if(0==0) {
            throw new NullPointerException();
        }

        doReturn(5).when(s).someMethod(anyLong(), any(Integer.class), any());
    }

    @Test
    public void testThree() {
        Something s = spy(new Something());
        doReturn(5).when(s).someMethod(anyLong(), any(Integer.class), any()); // no issues
    }
}

Observations :

  1. If I run the whole class, then all methods would FAIL. testThree throws InvalidUseOfMatchersException
  2. If I run the third method alone, then it would PASS.
  3. If i comment testOne and then run the whole run class, then testTwo would FAIL and testThree would PASS.

In my observation above, 2 and 3 are as expected. But I don't understand why testThree is also failing in observation 1. When I check the console, it shows that

This message may appear after an NullPointerException if the last matcher us returning an object like any() but the stubbed method signature expect a primitive argument.

So my question is Why should a test method fail due to an issue with a previous test method?

(Also, if I rename testOne to testZZ so that it executes last according to alphabetical order then testThree would PASS when test run at the class level.)

0

There are 0 best solutions below