class TaskPollRunnable implements Runnable { @Override public void run() { try { FileCleanTaskResponse poll = pollTasks(1); List<FileCleanTask> tasks = poll.getCleanTasks(); log.info("cleantasks:" + tasks); if (tasks.isEmpty()) { try { Thread.sleep(60000); } catch (InterruptedException e) { log.error("InterruptedException while sleeping",e); } } long startTimeMills = System.currentTimeMillis(); List<Future> futures = new ArrayList<>(); for (FileCleanTask task : tasks) { List<String> dirs = task.getCleanDirs(); log.info("cleandirs:" + dirs); dirs.stream().forEach(dir -> { Future future = executor.submit(new FileCleanRunnable(dir)); futures.add(future); }); } //等待所有线程执行结束 for (Future future : futures) { try { future.get(); } catch (InterruptedException e) { log.error("clean task interupt", e); } catch (ExecutionException e) { log.error("clean task ", e); } } log.info("ALL File clean thread finish,cost: {} ms", (System.currentTimeMillis() - startTimeMills)); } catch (Exception e) { log.error("TaskPollRunnable failed",e); } } 写UT,覆盖异常
时间: 2024-02-10 17:17:09 浏览: 121
针对以上代码,可以编写如下的 UT:
```
@Test
public void testTaskPollRunnable() throws Exception {
// 构造 mock 对象
FileCleanTaskResponse response = new FileCleanTaskResponse();
List<FileCleanTask> tasks = new ArrayList<>();
FileCleanTask task1 = new FileCleanTask();
task1.setCleanDirs(Arrays.asList("/tmp/dir1", "/tmp/dir2"));
tasks.add(task1);
response.setCleanTasks(tasks);
// 模拟 pollTasks 方法返回 response
when(mockedObject.pollTasks(1)).thenReturn(response);
// 创建线程池
ExecutorService executor = Executors.newFixedThreadPool(2);
// 构造 TaskPollRunnable 对象
TaskPollRunnable taskPollRunnable = new TaskPollRunnable();
taskPollRunnable.setExecutor(executor);
taskPollRunnable.setPollInterval(1000);
taskPollRunnable.setService(mockedObject);
// 启动线程
Thread thread = new Thread(taskPollRunnable);
thread.start();
// 等待 2 秒钟
Thread.sleep(2000);
// 验证异常
verify(mockedObject, atLeastOnce()).pollTasks(1);
verifyNoMoreInteractions(mockedObject);
// 关闭线程池
executor.shutdown();
}
```
以上 UT 验证了 TaskPollRunnable 的基本功能,以及异常处理能力。其中,需要将 pollTasks 方法的返回结果 mock 掉,以保证测试的可重复性。同时,为了验证是否正常处理了异常,使用了 verify 方法验证了 pollTasks 方法是否被调用,并且没有其他交互。最后,需要关闭线程池以释放资源。
阅读全文