有很多重构问题,有人可能已经回答过了。但是,我决定问自己的问题。我无法在下面的代码片段中将Thread.sleep(1000)重构为countdownlatch。在参加软件测试课程时,我遇到了一篇论文,"测试气味真的有害:实证研究"我想了解更多有关该主题领域的信息。谁能帮帮我吗?
try (Socket client = new Socket("localhost", connector.getLocalPort()))
{
OutputStream output = client.getOutputStream();
for (ByteBuffer buffer : lease.getByteBuffers())
{
output.write(BufferUtil.toArray(buffer));
}
Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter()
{
@Override
public void onHeaders(HeadersFrame frame)
{
try
{
// Close the connection just after
// receiving the response headers.
client.close();
closeLatch.countDown();
}
catch (IOException x)
{
throw new RuntimeIOException(x);
}
}
}, 4096, 8192);
parseResponse(client, parser);
// We need to give some time to the server to receive and process the TCP FIN.
Thread.sleep(1000);
Session session = sessionRef.get();
Assert.assertTrue(session.isClosed());
Assert.assertTrue(((HTTP2Session)session).isDisconnected());
}
答案 0 :(得分:1)
我担心在任何测试级别都没有逃脱等待。因为没有办法让你知道被测系统究竟何时会响应(有时它只是不响应)。但您可以转到UI测试中使用的Explicit wait。如果您不熟悉这个概念 - 显式等待是仅限于特定响应的智能等待。使用显式等待你基本上告诉你的测试,在它放弃之前,等待X单位(让我们假设50ms)的时间有最长的时间。
针对完整答案 - 您还可以创建一个处理请求的Worker thread,一旦获得响应,将自动唤醒测试线程。
更新:
以下是Java example测试多线程访问而不是休眠
@Test
public void concurrentAccessFromMultipleThreads() throws Exception {
final Counter counter = new Counter();
final CountDownLatch allThreadsComplete = #1
new CountDownLatch(threads); #1
final int callsPerThread = 100;
final Set values = new HashSet();
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i < callsPerThread; i++) {
values.add(counter.getAndIncrement());
}
allThreadsComplete.countDown(); #2
}
};
int threads = 10;
for (int i = 0; i < threads; i++) {
new Thread(runnable).start();
}
allThreadsComplete.await(10, TimeUnit.SECONDS); #3
int expectedNoOfValues = threads * callsPerThread;
assertEquals(expectedNoOfValues, values.size());
}