Mocking Singleton Class Constructor using Powemock

27 views Asked by At

The problem is exactly similar to the one described How to mock enum singleton with jmockit?. I am using powermock with Junit in Java.

there are some other singlton classes too without constructor which can be easily mocked with Powemock Whitebox set internal state method.

Basically for some enum singleton classes as following

public enum SingletonObject {
  INSTANCE;

  public callDB() {
    this.num = num;
  }

}

testing below class

public class MyClass {
  public void doSomething() {
    // some code
    SingletonObject.INSTANCE.callDB();
  }
}

using Whitebox set internal state is lokie following

SingletonObject mockSingleton = mock(Singelton.class);
DB db = mock(DB.class);
doReturn(db).when(mockSingleton, "callDB");
Whitebox.setInternalState(SingletonObject.class, "INSTANCE", mockSingleton); 

The above implementation is working, except for the cases where the singleton is also having constructor inializing things within itself like below.

public enum SingletonObject {
  INSTANCE;
  
  SingletonObject() {
    // some annoying initialization
  }

  public callDB() {
    this.num = num;
  }

}

using same above here is calling the enum constructor. I have tried using spy too but same result. So how can I mock this enum singleton without invoking its constructor?

0

There are 0 answers