I'd like to use strict mocks, at least when developing for the first time some tests against old code, so any methods invoked on my mock will throw an exception if I didn't specifically define expectations.
From what I've come to see, Mockito if I didn't define any expectations will just return null, which will later on cause a NullPointerException in some other place.
Is it possible to do that? If yes, how?
"Strict stubbing" is a new feature in Mockito 2 that drives cleaner tests and better productivity. The easiest way to leverage it is via Mockito's JUnit support ( MockitoJUnit ) or Mockito Session ( MockitoSession ).
lenient() to enable the lenient stubbing on the add method of our mock list. Lenient stubs bypass “strict stubbing” validation rules. For example, when stubbing is declared as lenient, it won't be checked for potential stubbing problems, such as the unnecessary stubbing described earlier.
For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.
method. Mockito is the most popular mocking framework used for testing Java applications. It is better than any other testing and mocking framework, such as EasyMock.
What do you want it to do?
You can set it to RETURN_SMART_NULLS, which avoids the NPE and includes some useful info.
You could replace this with a custom implementation, for example, that throws an exception from its answer
method:
@Test
public void test() {
Object mock = Mockito.mock(Object.class, new NullPointerExceptionAnswer());
String s = mock.toString(); // Breaks here, as intended.
assertEquals("", s);
}
class NullPointerExceptionAnswer<T> implements Answer<T> {
@Override
public T answer(InvocationOnMock invocation) throws Throwable {
throw new NullPointerException();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With