The Singleton Pattern Revisited
Need to test a singleton ?
Suppose you have singleton class A:
class A {
public static A getInstance() {...}
private A() { ... }
public int doStuff() { ... }
}
How can you test it if you can’t use your mocks ? Simple put it in a package and make ASingleton that creates A using a constructor package default ! Since your tests run in the same package you will be able to extend it and use your mocks while still having a semi-private constructor.
class A {
A() { ... }
public int doStuff() { ... }
}
class ASingleton {
private ASingleton() {}
public static A getInstance() { ... }
}