2015-05-16 51 views
2

我已经写了一个线程池,我不能为该类编写Junits(PowerMock)。静态字段为嘲笑与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)); 
} 
} 

虽然惩戒此类我得到NullPointerException异常在该行PROP_READER.loadProperties( “虚拟”);

我的测试案例是: -

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

回答

0

首先,你需要设置你的枚举的内部状态枚举是final类 和枚举的实例将在类装载时的装载

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

,如果它仍然没有工作,你需要看到的类的其中多个成员需要在内部状态设置