我编写了一个线程池,但我无法为该类编写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);
答案 0 :(得分:1)
首先,您需要设置枚举的内部状态,因为枚举是最终类 并且将在类加载
上加载枚举的实例PowerMockito.mockStatic(ThreadPool .class);
然后
doNothing().when(mockInstance).loadProperties(any(String.class));
然后嘲笑
@RunWith(PowerMockRunner.class)
@PrepareForTest({ThreadPool.class})
不要忘记在测试中添加以下注释
http://website.com --> cstp://website.com
ftp://website.com --> oftp://website.com
https://website.com --> ctcps://website.com
如果它仍然不起作用,你需要看看你需要在内部状态中设置哪个类的更多成员