private class TaskPollRunnable implements Runnable { @Override public void run() { FileCleanTaskResponse poll = pollTasks(1); List<FileCleanTask> tasks = poll.getCleanTasks(); log.info("cleantasks:"+tasks); if(tasks.isEmpty()){ try { Thread.sleep(60000); } catch (InterruptedException e) { e.printStackTrace(); } } 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));//1个网元1个线程 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)); }写 ut
时间: 2024-02-10 07:05:16 浏览: 77
implements Runnable
好的,以下是该代码的一个可能的UT:
```java
@Test
public void testTaskPollRunnable() throws ExecutionException, InterruptedException {
// 准备测试数据
FileCleanTaskResponse response = new FileCleanTaskResponse();
List<FileCleanTask> tasks = new ArrayList<>();
FileCleanTask task1 = new FileCleanTask();
List<String> dirs1 = new ArrayList<>();
dirs1.add("/tmp/dir1");
dirs1.add("/tmp/dir2");
task1.setCleanDirs(dirs1);
tasks.add(task1);
response.setCleanTasks(tasks);
// mock pollTasks方法返回值
when(mockedFileCleanService.pollTasks(anyInt())).thenReturn(response);
// mock executor.submit方法,直接调用run方法执行
doAnswer(invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
}).when(mockedExecutor).submit(any(Runnable.class));
// 执行测试
TaskPollRunnable taskPollRunnable = new TaskPollRunnable();
taskPollRunnable.setFileCleanService(mockedFileCleanService);
taskPollRunnable.setExecutor(mockedExecutor);
taskPollRunnable.run();
// 验证结果
verify(mockedFileCleanService, times(1)).pollTasks(1);
verify(mockedExecutor, times(2)).submit(any(Runnable.class)); // 共两个目录,两个线程
}
```
需要注意的是,该UT使用了Mockito框架,需要先导入Mockito相关的依赖。同时,由于该代码中使用了线程池,需要使用Mockito的doAnswer方法模拟线程池的submit方法,使得测试中的线程直接调用run方法执行。
阅读全文