I have a test class that looks like this:
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
public class SomeTest {
@Mock
Object someObj;
@Before
public void before() {
MockitoAnnotations.openMocks(this);
}
@Test
public void testNullPointer() {
Mockito.when(someObj.toString()).thenReturn("1");
}
}
When I run mvn clean test
under the root directory of this project, it said that the testcase triggeredNullPointerException
, stack tree shows that someObj
is null.
I was using org.mockito::mockito-core::4.0.0
and junit::junit::4.13.0
.
Seems like before() method is not executed. Any ideas why? Tks in advance.
CodePudding user response:
You are missing annotation on your class:
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
...
}
CodePudding user response:
When running this test you'll get this error above the stacktrace:
testNullPointer(org.example.SomeTest) Time elapsed: 0.368 sec <<< ERROR!
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
The interesting part here is the first bullet - you cannot stub the hashCode
method. If you replace it by some method that can be stubbed, the test will pass. E.g.:
Mockito.when(someObj.toString()).thenReturn("yay!");