Search code examples
junitsingleton

Different Singleton instances with JUnit tests


I have a standalone singleton which successfully passes the test. But with a group of tests this fails since once a singleton is defined it does not allow to reset the instance.

Any ideas about how to go about this?


Solution

  • Don't use a singleton.

    Specifically, the only difference between a singleton and a global variable is that the singleton tries to enforce a single instance (by making the constructor private, for example).

    Instead, make the constructor public and write tests using new instances. In your actual program, use getInstance() to get the canonical global instance (or use an IOC container).

    And remember that singletons are pathological liars.

    If you're still too comfortable with the idea of a Singleton, instead of making the constructor public you can add a public (and static) factory method to create instances in a way that can't be used by accident, e.g.:

    public static MyClass TEST_CreateInstance() {
      return new MyClass();
    }