I am facing a scenario where I have to mock a certain method only when it is being invoked from very specific method. For example here is the sample code:
public class TestMethod {
public boolean testMethod() {
return false;
}
}
public class ClassToBeTested {
private TestMethod testMethod;
public ClassToBeTested() {
testMethod = new TestMethod();
}
public boolean evaluateSomething() {
boolean evaluation1Ans = evaluate1();
boolean evaluation2Ans = evaluate2();
return !evaluation1Ans && evaluation2Ans;
}
public boolean evaluate1() {
boolean expr = testMethod.testMethod();
return expr;
}
public boolean evaluate2() {
return testMethod.testMethod() && evaluateBooleanExpression();
}
private boolean evaluateBooleanExpression() {
return true;
}
}
public class MockitoExperiement {
@Test
public void testEvaluateSomething() throws Exception {
ClassToBeTested classToBeTested = new ClassToBeTested();
TestMethod testMethod = mock(TestMethod.class);
when(testMethod.testMethod()).thenAnswer((Answer<Boolean>) invocationOnMock -> {
if(new Object() {}
.getClass()
.getEnclosingMethod()
.getName().equals("evaluate2")) return true;
else
return false;
});
boolean flag = classToBeTested.evaluateSomething();
System.out.print("");
}
}
Here despite doing conditional mocking I am still receiving false from the method to be invoked. Where I am making a mistake in this sample?