I have code similar to this
class superClass {
public String transform(String str) {
//lots of logic including ajax calls
return("Modified"+str);
}
}
class baseClass extends superClass {
private FetchData fetchData;
baseClass(FetchData fetchData) {
this.fetchData = fetchData;
}
public String parse() {
String str = fetchData.get();
//some more logic to modify str
return transform(str);
}
}
and I am using mockito and junit to test it. I am mocking the baseClass
and doing something like this
baseClass baseMock = Mockito.mock(baseClass.class);
Mockito.when(baseMock.parse()).thenCallRealMethod();
Mockito.when(baseMock.transform()).thenReturn("Something");
How can I inject the mock fetchData
, as it is injected through the constructor?
You can use Mockito.spy
(http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#spy):
baseClass object = new baseClass(new FetchData());
baseClass spy = Mockito.spy(object);
Mockito.when(spy.parse()).thenCallRealMethod();
Mockito.when(spy.transform()).thenReturn("Something");
Your problem is of a different nature: you created hard to test code. That is the thing with constructors: one has to be really careful about what they are doing.
The other thing is that you directly "ran" into "prefer composition over inheritance". It might be tempting to simply extend some other class to inherit some helpful behavior - but when you are doing that, you run exactly in such kind of problems!
My kinda non-answer: step back, and have a close look into your design if that is really the best solution. Probably you watch those videos first to understand what I am talking about. If you have some experienced folks around, talk to them; and have them review your design.
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