Search code examples
jmockitprivate-methods

Jmockit- mock Private Medhod to return complex object, and then use that for Expectations()


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:

  1. Both the private method and the method to test are in the same class that needs to be tested
  2. Need to call the private method to return a mock implementation of it
  3. Use this mock implementation to return the final answer

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.


Solution

  • 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());
    }