0

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.

PNS
  • 19,295
  • 32
  • 96
  • 143
  • Is this useful? https://stackoverflow.com/questions/9697531/how-to-mock-a-static-final-variable-using-junit-easymock-or-powermock – Shailesh Suryawanshi Jul 28 '21 at 14:44
  • Not sure I understood your problem, but maybe `MockBean` is what you are looking for. Have a look at https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/MockBean.html – Luis Celestino Jul 28 '21 at 14:58

0 Answers0