Different Singleton instances with JUnit tests

后端 未结 7 1072
遥遥无期
遥遥无期 2021-01-31 17:41

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.

7条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-31 18:04

    I highly recommend moving away from Singletons as a design pattern, and using Singleton as a scope (Dependency Injection). This would simply make your problem go away.

    But assuming you are stuck in the world of Singletons, then you have a few options depending on if you are testing the Singleton or the dependency.

    If you are testing the dependant item then you can mock the Singleton using PowerMock and JMockIt. See my previous post about mocking Runtime.getRuntime for instructions on how to go about this.

    If you are testing the Singleton then you need to relax the rules on construction, or give the Singleton a "Reset" method.

提交回复
热议问题