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 ...
I consider the class that implements methodToTest
is named ClassToTest
OtherObject
ClassToTest
ClassToTest
ClassToTest
object and create a setter for the factoryyour 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
// ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With