Is there any way of mocking a really complex object, statically initialized in a class, without modifying source code?
The code looks something like this.
public class SomeType {
private static final ComplexType TYPE = new ComplexType();
public SomeType() {}
public Object process(int id, String content) {
...
TYPE.something();
...
}
}
Attempting to test the behavior of the SomeType
class by calling
new SomeType().process(1, "<some text>");
requires mocking somehow the ComplexType
object, which has numerous other complex objects statically initialized in its definition, plus network-intensive operations during initialization. As a result, mock()
or spy()
do not work, since the ComplexType
object gets initialized on referencing the SomeType
class. It appears that, to mock the ComplexType
object all its complex dependencies need to be prepared, which makes the test code complicated.
Another approach suggested is modifying the static final
field TYPE
via reflection. However that won't work either, since it takes place after the initialization of TYPE
, so the error caused by the initialization has already taken place.