Java 如何为ThreadPoolExecutor编写Junit测试
如何为以下函数编写Junit测试。ParallelExecutor扩展ThreadPoolExecutor,WorkerThread将在值更改(侦听器)时调用lock.countDown()。WorkerThread是一个三方类。请让我知道如何让测试减少闩锁Java 如何为ThreadPoolExecutor编写Junit测试,java,junit,threadpoolexecutor,Java,Junit,Threadpoolexecutor,如何为以下函数编写Junit测试。ParallelExecutor扩展ThreadPoolExecutor,WorkerThread将在值更改(侦听器)时调用lock.countDown()。WorkerThread是一个三方类。请让我知道如何让测试减少闩锁 public static void OpenScreen() throws InterruptedException { //some job...3 party screen // creating the Thread
public static void OpenScreen() throws InterruptedException {
//some job...3 party screen
// creating the ThreadPoolExecutor
final ParallelExecutor executorPool = new ParallelExecutor(10);
final CountDownLatch latch = new CountDownLatch(0);
// start the monitoring thread
final MyMonitorThread monitor = new MyMonitorThread(executorPool, 3);
final Thread monitorThread = new Thread(monitor);
monitorThread.start();
// monitorThread.start();
// submit work to the thread pool
for (int i = 0; i < 10; i++) {
executorPool.execute(new WorkerThread(("cmd" + i), latch));
}
latch.await();
Thread.sleep(30000);
// shut down the pool
executorPool.shutdownNow();
// shut down the monitor thread
monitor.shutdown();
}
publicstaticvoidopenscreen()抛出InterruptedException{
//一些工作…3党的屏幕
//创建ThreadPoolExecutor
最终并行执行器执行池=新的并行执行器(10);
最终倒计时闩锁=新倒计时闩锁(0);
//启动监视线程
最终MyMonitorThread监视器=新的MyMonitorThread(executorPool,3);
最终线程监视器线程=新线程(监视器);
monitorThread.start();
//monitorThread.start();
//将工作提交到线程池
对于(int i=0;i<10;i++){
executorPool.execute(新的WorkerThread((“cmd”+i),闩锁));
}
satch.wait();
睡眠(30000);
//关闭游泳池
executorPool.shutdownNow();
//关闭监视器线程
monitor.shutdown();
}
那么您想测试什么?:-)是否调用了execute方法?计数有效吗?如果其中一项任务需要太多时间才能执行,时间规划是否有效?当openScreen()
方法返回时,所有作业都已完成
如果您想进行单元测试,可以使用mock(为此,我将把这个功能提取到一个单独的类中,在这个类中,为新类传递/注入像pool和monitor这样的依赖项)。在那里,您可以验证是否正确调用了这些方法