How to mock another method in the same class which is being tested?
As per @Totoro's answer, this is just a summary here.
- Annotate the object for the class you are testing with the
@Spy
annotation.
So this:
@Spy
@InjectMocks
MyClassUnderTest myClassUnderTest;
instead of just
@InjectMocks
MyClassUnderTest myClassUnderTest;
- Use
doReturn()
instead ofwhen.thenReturn()
whenever asking for the mocked object from the class spyed on (class under test).
doReturn(X).when(myClassUnderTest).method(any())
I ran into this yesterday, for spies is best to do:
doReturn(X).when(spy).method(any())
Taking this approach will result in brittle tests which will need to change if you refactor your class under test. I would highly recommend that you try to assert your expected test results by checking state of SomeClass
rather than relying on mocks.
If you do indeed need to mock MethodB
then this is an indication that maybe the behaviour in MethodB
actually belongs in a separate class which you could then test the interaction of SomeClass
with via mocks
if you do indeed need to do what you ask for then a PartialMock is what you want.
you probably want to create a partial mock of some class but indicate that calls to MethodA
should call the actual method but then mock MethodB
You can see how to use them in the Mockito documentation
As stated in their documentation though Partial mocks are a code smell, though they have identified some explicit use cases.