Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock "inner" object with Mockito

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 ...

like image 852
RRZ Europe Avatar asked Apr 02 '13 08:04

RRZ Europe


1 Answers

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
        // ...
    }
}
like image 93
rcomblen Avatar answered Sep 22 '22 23:09

rcomblen