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

Static Field as Null when mocking Enums with PowerMock

我已经编写了一个线程池,但我无法为此编写 Junits(PowerMock) class。

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));
}
}

在模拟这个 class 时,我在行 PROP_READER.loadProperties("DUMMY");

我的测试用例是:-

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

首先,您需要设置枚举的内部状态,因为枚举是最终的 class 并且枚举的实例将在 class 加载

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

然后

PowerMockito.mockStatic(ThreadPool .class);

然后嘲讽

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

不要忘记在测试中添加以下注释

@RunWith(PowerMockRunner.class)
@PrepareForTest({ThreadPool.class})

如果仍然无法正常工作,您需要查看 class 的哪个成员需要在内部状态

中设置