I am trying to mock a method and want to execute the internal logic as is when called.
The method returns void so When I am using when(MockedObject.methodReturingVoid(any())).callRealMethod();
It gives error that the method return void.
so i tried with doCallRealMethod().when(MockedObject).methodReturingVoid(any()));
it give nullPointerException when as any() return null.
How can I mock this method which I want to be called with its internal logic, when the method returns void.
I am trying to mock a method and want to execute the internal logic as is when called.
The method returns void so When I am using when(MockedObject.methodReturingVoid(any())).callRealMethod();
It gives error that the method return void.
so i tried with doCallRealMethod().when(MockedObject).methodReturingVoid(any()));
it give nullPointerException when as any() return null.
How can I mock this method which I want to be called with its internal logic, when the method returns void.
Share Improve this question asked Feb 7 at 12:58 JefJef 1441 gold badge1 silver badge10 bronze badges 2 |1 Answer
Reset to default 0Suppose you have the class you want to test:
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SomeClass {
public void actual() {
log.info("Calling the actual method");
}
public void toMock() {
log.warn("This should not have been invoked; mocking this one");
}
public void wrapper(String someArgument) {
log.info("Calling wrapper, which invokes actual once and toMock once, argument value: {}", someArgument);
actual();
toMock();
}
}
As the names suggest, actual and wrapper are to be actually invoked, while toMock will be mocked.
Then, you could write:
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;
class SomeClassTest {
@Test
void test() {
SomeClass mock = mock(SomeClass.class);
doCallRealMethod().when(mock).actual();
doCallRealMethod().when(mock).wrapper(any());
mock.wrapper("Actual argument");
verify(mock, times(1)).actual();
verify(mock, times(1)).toMock();
}
}
As a brief explanation, we are setting up mockito to invoke the actual methods for actual and wrapper. We are omitting configuration for toMock.
Then we check that actual has been invoked, as well as the mock for toMock.
The code above prints:
--- [main] INFO ---SomeClass -- Calling wrapper, which invokes actual once and toMock once, argument value: Actual argument
--- [main] INFO ---SomeClass -- Calling the actual method
Edit: including formal and actual parameter.
I am using lombok and slf4j, but you can simply use System.out.println, if you prefer.
any()
always returns null. Are you sure thatMockedObject
is a Mockito.mock instance? – knittl Commented Feb 7 at 13:33