JUnit测试意外行为

时间:2017-10-26 11:41:59

标签: java junit

我运行了几个JUnit测试来测试消息解析系统。

使用3s超时单独运行测试是可以的 - 它们都通过了。

一次运行测试会导致问题,我经常会看到以下错误消息:

java.lang.AssertionError: Expected <3> but collection size <0>

我可以通过将超时增加到30秒来解决这个问题,但在这种情况下,我发现Test1由于某种原因重新运行。这是我在运行Test6时在日志中看到的并将runforMilliseconds(3000, () -> messageProcessor.start());上的超时增加到runforMilliseconds(30000, () -> messageProcessor.start()); ...因此导致了很多断言错误:

[ForkJoinPool.commonPool-worker-1] Started parsing Test1
[ForkJoinPool.commonPool-worker-6] Started parsing Test6
[ForkJoinPool.commonPool-worker-2] Started parsing Test2
[ForkJoinPool.commonPool-worker-5] Started parsing Test5
[ForkJoinPool.commonPool-worker-3] Started parsing Test3

这是单元测试的一个例子:

Test1.java

@Before
public void setUp() throws Exception {
    test1Mapper.deleteAll();
    messageTestMapper.deleteAll();
    setupMessages();
}

@Test
public void Test1() throws Exception {
    messageTestMapper.insertOne(new TestMessage(message1)):
    messageTestMapper.insertOne(new TestMessage(message2)):
    messageTestMapper.insertOne(new TestMessage(message3)):

    runforMilliseconds(3000, () -> messageProcessor.start());
    List<TestMessageDetails) actualTestMessageDetails = test1Mapper.select();
    assertThat(actualTestMessageDetails, hasSize(3));
}

@SneakyThrows
private void runforMilliseconds(int n, Runnable runnable) throws Exception {
    try {
        CompleteableFuture.runAsync(runnable).get(n, TimeUnit.MILLISECONDS);
    }
    catch (TimeoutException e) {
        log.info("End running");
    }
}

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

您的所有单元测试是否都使用相同的var pdf = path.join(__dirname, '../../testoutput.pdf'); pdfJsLib.getDocument(pdf).then(function(doc){ var promises = []; for(i = 1; i <= doc.numPages; i++){ //promises.push(doc.getPage(i)); doc.getPage(i).then(function(page){ promises.push(page.getTextContent()); var response = []; if(i == doc.numPages + 1){ var promiseLimiter = promises.length; Promise.all(promises).then(function(data){ response.push(data[0]); if(promiseLimiter == doc.numPages){ res.status(200).json(response); } }) } }) test1Mapper变量?如果是这样,请考虑为每个测试提供各自的映射变量,以便您可以并行运行它们,而不会有一个测试影响其他测试的结果。