I have this situation that I need to test where re-factoring code is not possible (due to organizational reasons :( ).
class ClassToTest {
private ComplexObject createComplexObject() throws SomeException{
//create the complex object
}
public ReturnObject methodToTest(RequestObject reqObj) throws SomeOtherException {
ComplexObject complexObj = createComplexObject();
int answer = complexObj.doSomething();
return new ReturnObject(answer);
}
}
Most of the samples i see are around invoking private methods and have them return a String or an int etc. So here the requirement is a little extra:
Please advice on this. All of the examples i see are just to the point of mocking a private method to return String
/int
, whereas here i need a complex object(which is mocked itself) and then use it to return the final answer from within the method that's under test.
You don't want to mock the private method (which is just an internal implementation detail), but the ComplexObject
dependency. So:
@Test
public void exampleTest(@Mocked final ComplexObject anyCmplxObj) throws Exception
{
new Expectations() {{ anyCmplxObj.doSomething(); result = 123; }};
RequestObject request = new RequestObject(...);
ReturnObject ret = new ClassToTest().methodToTest(request);
assertEquals(123, ret.getAnswer());
}