Mock "inner" object with Mockito

java, junit, mockito

Solution

I consider the class that implements `methodToTest` is named `ClassToTest`

- Create a factory class for `OtherObject`

- Have the factory as a field of `ClassToTest`

- either

- pass the factory as parameter of the constructor of `ClassToTest`

- or initialize it when allocating the `ClassToTest` object and create a setter for the factory

your test class should look like

public class ClassToTestTest{
    @Test
    public void test(){
        // Given
        OtherObject mockOtherObject = mock(OtherObject.class);
        when(mockOtherObject.methodX()).thenReturn("methodXResult");
        OtherObjectFactory otherObjectFactory = mock(OtherObjectFactory.class);
        when(otherObjectFactory.newInstance()).thenReturn(mockOtherObject);
        ClassToTest classToTest = new ClassToTest(factory);

        // When
        classToTest.methodToTest(input);

        // Then
        // ...
    }
}

Problem

Quite new to unittesting and mockito, I have a method to test which calls a method on a new object. how can I mock the inner object? ``` methodToTest(input){ ... OtherObject oo = new OtherObject(); ... myresult = dosomething_with_input; ... return myresult + oo.methodX(); } ``` can I mock oo to return "abc"? I really do only want to test my code, but when I mock "methodToTest" to return "42abc", then I will not test my "dosomething_with_input"-code ...

Original source