我想用以下方法测试单例类的行为:
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;
}
}
然后我有一个带有几个测试方法的测试类,它们调用init
了几次:
@RunWith(PowerMockRunner.class)
@PrepareForTest(SomeSingleton.class)
public class SomeSingletonTest {
@Test
public void testGetInstanceSunnyDay()
{
[...]
SomeSingleton.init(...);
[...]
SomeSingleton.getInstance();
[...]
}
@Test
public void testGetInstanceRainyDay()
{
[...]
SomeSingleton.init(...); // IllegalStateException
[...]
SomeSingleton.getInstance();
[...]
}
}
当我这样做时,我总是IllegalStateException
在第二次测试中获得,因为instance != null
.
如何init
在一个测试类中运行多个测试?
testGetInstanceSunnyDay
将and放在testGetInstanceRainyDay
2 个单独的类中解决了这个问题,但我想知道是否有更好的解决方案。