【发布时间】:2016-12-20 10:47:40
【问题描述】:
Awaitility 是对并发生产代码进行单元测试的绝佳工具。
问题:有没有工具可以简化并发测试代码的编写?
假设我想测试java.util.concurrent.LinkedBlockingQueue。
public class BlockingQueueTest {
private LinkedBlockingQueue<String> out;
@Before
public void setUp() {
out = new LinkedBlockingQueue<>();
}
@Test
public void putThenGet() throws InterruptedException {
// that's easy because it can be done in one thread
out.put("Hello");
String taken = out.take();
assertThat(taken).isEqualTo("Hello");
}
@Test
public void getBeforePut() throws InterruptedException {
// that's more tricky because it can't be done with one thread
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(() -> {
Thread.sleep(100);
out.put("Hello");
return null;
});
executorService.shutdown();
String taken = out.take();
assertThat(taken).isEqualTo("Hello");
}
}
getBeforePut() 编码不好玩。有没有办法让它变得不那么难读,像这样?
@Test
public void getBeforePut2() throws InterruptedException {
// Wanted: DSL for concurrent test-code
Concurrently.sleep(100, TimeUnit.MILLISECONDS).andThen(() -> out.put("Hello"));
String taken = out.take();
assertThat(taken).isEqualTo("Hello");
}
【问题讨论】:
-
你为什么不自己实现
Concurrently类呢?你已经有了它应该执行的代码,现在只是重构的问题。结果将有大约 30 行代码。
标签: java unit-testing kotlin junit concurrency