Consider the following method:
public boolean isACertainValue() {
if(context.getValueA() != null && context.getValueA().toBoolean() == true) {
When you are invoking
Mockito.when(spy.isCertainValue()).thenReturn(true);
the method isCertainValue()
is getting called here. This is how Java works: to evaluate the argument of Mockito.when
, the result of spy.isCertainValue()
must be evaluated so the method must be called.
If you don't want that to happen, you can use the following construct:
Mockito.doReturn(true).when(spy).isCertainValue();
This will have the same mocking effect but the method won't be called with this.
This code is correct:
Mockito.when(contextMock.getType()).thenReturn(ContextType.certainType);
But you are getting NullPointerException because you didn't define the Mocking value that should be defines, well I'm using Spring, in my context file when I define @Autowired
bean I define it this way:
<bean id="contextMock" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.example.myspringproject.bean.ContextMock" />
</bean>