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:
NPE
would be thrown because I usedany()
to match a primitive argumentNPE
would be thrown because I usedthrow new NullPointerException()
- 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 :
- If I run the whole class, then all methods would FAIL.
testThree
throwsInvalidUseOfMatchersException
- If I run the third method alone, then it would PASS.
- If i comment
testOne
and then run the whole run class, thentestTwo
would FAIL andtestThree
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.)