When doing UnitTest you want to test observable behavior, not code.
Observable behavior is either:
- return values of (public) interface methods
- interaction with other objects (dependencies)
- changes of the object state (usually changes of getter results)
These are testet through the public interface of the class under test (CUT). these public interface does not nessessarrily mean public methods, but rather means methods which ar expected to be called by the code using the CUT.
In your case you want to test the state change of the object as a side effect when calling the method.
But the problem is that your code does not change the objects state, so nothing can be tested.
Technically you could raise the visibility of your the getter method and mock it with Mockito, but this is as useless as the whole code.
Amendment
I write this because the OP has an assignment to do it. I'd like to stress that this is not the way it should be done.
since the method to be observed is private you have 2 options:
make the method to be observed visible to the test class.
Then you can use regular Mockito functionality:
/*ClassUnderTest CUT */
public void doSomething(){
if(someCondition){
int foo = doThis();
}
// ----
// remaining code
}
/* package private, test class should be in same package */
int doThis(){
return 100;
}
/* TestClass */
@Test
public void doSomething__conditionTrue__callesMemberMethod(){
ClassUnderTest cut = Mockito.spy(new ClassUnderTest());
// anything needed to make the condition true
cut.doSomething();
Mockito.verify(cut).doThis();
}
@Test
public void doSomething__conditionFalse__doesNotCallMemberMethod(){
ClassUnderTest cut = Mockito.spy(new ClassUnderTest());
// anything needed to make the condition false
cut.doSomething();
Mockito.verify(cut,never()).doThis();
}
use PowerMock(-ito)
but PowerMockito changes the byte code of the CUT and therefore you arn't really testing your CUT. I strongly suggest not to use it unless you have to test legacy code which is untestable otherwise.