DP_*_*DP_ 4 java junit singleton unit-testing
我想用以下方法测试单例类的行为:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我有一个带有几个测试方法的测试类,它们会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();
[...]
}
}
Run Code Online (Sandbox Code Playgroud)
当我这样做时,我总是得到IllegalStateException第二次测试,因为instance != null.
如何init在一个测试类中运行多个测试?
把testGetInstanceSunnyDay和testGetInstanceRainyDay2个单独的类解决了这个问题,但我不知道是否有更好的解决方案.
从根本上说,单身人士很难测试,正是因为这种事情.你可以添加一个clearStateForTesting方法:
static void clearStateForTesting() {
instance = null;
}
Run Code Online (Sandbox Code Playgroud)
......但我建议你尽可能避免使用单身模式.
另请注意,您的单例实现目前不是线程安全的.如果你真的需要使用单例,那么有更好的实现.
| 归档时间: |
|
| 查看次数: |
7394 次 |
| 最近记录: |