使用PowerMock模拟枚举时,静态字段为空



我已经写了一个线程池,我不能为这个类写Junits(PowerMock)。

public enum ThreadPool {
INSTANCE;
private static final String THREAD_POOL_SIZE = "threadpool.objectlevel.size";
private static TPropertyReader PROP_READER = new PropertyReader();
private final ExecutorService executorService;
private static final ILogger LOGGER = LoggerFactory
        .getLogger(ReportExecutorObjectLevelThreadPool.class.getName());
ThreadPool() {
    loadProperties();
    int no_of_threads = getThreadPoolSize();
    executorService = Executors.newFixedThreadPool(no_of_threads);
}
public void submitTask(Runnable task) {
    executorService.execute(task);
}
private static void loadProperties() {
    try {
        PROP_READER.loadProperties("Dummy");
    } catch (final OODSystemException e) {
        LOGGER.severe("Loading properties for app failed!");
    }
}
private int getThreadPoolSize() {
    return Integer.valueOf(PROP_READER
            .getProperty(THREAD_POOL_SIZE));
}
}

在嘲笑这个类时,我在PROP_READER.loadProperties("DUMMY");

中获得NullPointerException

我的测试用例是:-

PowerMockito.whenNew(PropertyReader.class).withNoArguments().thenReturn(mockPropertyReader);
PowerMockito.doNothing().when( mockPropertyReader,"loadProperties",anyString());
mockStatic(ThreadPool.class);

首先你需要设置enum的内部状态,因为enum是final类枚举的实例将在类加载

时加载。
ThreadPool mockInstance = mock(ThreadPool .class);
Whitebox.setInternalState(ThreadPool.class, "INSTANCE", mockInstance);
然后

PowerMockito.mockStatic(ThreadPool .class);

然后是mock

doNothing().when(mockInstance).loadProperties(any(String.class));

不要忘记在测试

中添加以下注释
@RunWith(PowerMockRunner.class)
@PrepareForTest({ThreadPool.class})

如果它仍然不工作,你需要看看你需要在内部状态

中设置更多的类成员

最新更新