gpt4 book ai didi

java - 如何编写并发单元测试

转载 作者:行者123 更新时间:2023-11-30 08:30:23 25 4
gpt4 key购买 nike

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");
}

最佳答案

使用 TestNG对我来说是最简单的方法:

 @Test(threadPoolSize = 10, invocationCount = 15, timeOut = 1000)
public void testPut(){
out.put("Hello");
}

此测试将在 10 个线程中运行 15 次,并且应该不会超过 1000 毫秒。

您还可以创建依赖于其他测试的测试

@Test(dependsOnMethods = "testPut")
public void testGetAfterPut{
String taken = out.take();

assertThat(taken).isEqualTo("Hello");
}

关于java - 如何编写并发单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41240505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com