I want to test the behavior of a singleton class with the following methods:
public class SomeSingleton { private final static int DEFAULT_VALUE1 = ...; private final static int DEFAULT_VALUE2 = ...; private static SomeSingleton instance; public static void init(int value1, int value2) { if (instance != null) { throw new IllegalStateException("SomeSingleton already initialized"); } instance = new SomeSingleton(value1, value2); } public static getInstance() { if (instance == null) { init(DEFAULT_VALUE1, DEFAULT_VALUE2); } return instance; } }
And then I have a test class with several test methods that call init
several times:
@RunWith(PowerMockRunner.class) @PrepareForTest(SomeSingleton.class) public class SomeSingletonTest { @Test public void testGetInstanceSunnyDay() { [...] SomeSingleton.init(...); [...] SomeSingleton.getInstance(); [...] } @Test public void testGetInstanceRainyDay() { [...] SomeSingleton.init(...);
When I do this like this, I always get IllegalStateException
in the second test, because instance != null
.
How to run multiple tests involving init
in one test class?
Putting testGetInstanceSunnyDay
and testGetInstanceRainyDay
in 2 separate classes solves the problem, but I wonder if there is a better solution.
source share