【发布时间】:2019-01-22 12:59:10
【问题描述】:
如何避免在单元测试中手动休眠。
假设在下面的代码中,Process 和 notify 需要大约 5 秒的时间来处理。所以为了完成处理,我增加了 5 秒的睡眠时间。
public class ClassToTest {
public ProcessService processService;
public NotificationService notificationService;
public ClassToTest(ProcessService pService ,NotificationService nService ) {
this.notificationService=nService;
this.processService = pService;
}
public CompletableFuture<Void> testMethod()
{
return CompletableFuture.supplyAsync(processService::process)
.thenAccept(notificationService::notify);
}
}
有没有更好的方法来处理这个问题?
@Test
public void comletableFutureThenAccept() {
CompletableFuture<Void> thenAccept =
sleep(6);
assertTrue(thenAccept.isDone());
verify(mocknotificationService, times(1)).notify(Mockito.anystring());
}
【问题讨论】:
-
这个方法到底测试什么?假设另一种方法总是在五秒钟内完成?并且被测方法与单元测试在同一个类中?
-
被测方法不在同一个Test类中,这只是为了展示一些示例代码。要测试的方法在其他类中并注入我的Test类中。我想了解如何避免在单元测试中睡觉。作为我正在测试的系统(某些方法可能需要随机的时间)
-
所示的测试不测试任何东西,除了该方法最终将完成(或在五秒的任意时间间隔内)。这个方法实际上应该测试什么?
-
更新了代码..抱歉造成混乱