How I can mock with Mockito other classes in my class which is under test?
For example:
MyClass.java
class MyClass {
public boolean performAnything() {
AnythingPerformerClass clazz = new AnythingPerformerClass();
return clazz.doSomething();
}
}
AnythingPerformerClass.java
class AnythingPerformerClass {
public boolean doSomething() {
//very very complex logic
return result;
}
}
And test:
@Test
public void testPerformAnything() throws Exception {
MyClass clazz = new MyClass();
Assert.assertTrue(clazz.performAnything());
}
Can I spoof AnythingPerformerClass
for excluding unnecessary logic from AnythingPerformerClass
? Can I override doSomething()
method for simple return true
or false
?
Why I specify Mockito, because I need it for Android testing with Robolectric.
As it currently is (both declaration and instantiation of the
AnythingPerformerClass
inside a method, it's not possible to mock theAnythingPerformerClass
using only Mockito.If possible, move both the declaration and the instantiation of
AnythingPerformerClass
to the class level: declare an instance variable of typeAnythingPerformerClass
and have it instantiated by the constructor.That way, you could more easily inject a mock of
AnythingPerformerClass
during test, and specify its behaviour. For example:or to test error handling:
You can set what to return in Mockito.
You could refactor
MyClass
so that it uses dependency injection. Instead of having it create anAnythingPerformerClass
instance you could pass in an instance of the class to the constructor ofMyClass
like so :You can then pass in the mock implementation in the unit test
Alternatively, if your
AnythingPerformerClass
contains state then you could pass aAnythingPerformerClassBuilder
to the constructor.