Run junit test certain amount of time

混江龙づ霸主 提交于 2019-12-23 19:38:57

问题


I want to test something for a while, say 5 seconds, and then pass the test if nothing wrong has been asserted. Is this possible with annotations? Can something like @Test(uptime=5000) be used?


回答1:


Revised answer after question was edited

Fundamentally it feels like you're testing the wrong thing here - it seems very odd for "nothing happening" to be a sign of success.

If you want to prove that your algorithm can run for a certain amount of time without failing, I would actually extract out a single cycle, then write a test of something like:

@Test
public void fineForFiveSeconds() {
    long start = System.nanoTime();
    long end = start + TimeUnit.SECONDS.toNanos(5);
    while (System.nanoTime < end()) {
        test.executeOneIteration();
    }
}

This way you don't have a separate thread which has to kill the working code, etc.

Original answer

This answer was written before the question indicated that timing out was a sign of success, not failure.

I think you just want the timeout attribute in the @Test annotation:

@Test(timeout = 5000)

with documentation:

Optionally specify timeout in milliseconds to cause a test method to fail if it takes longer than that number of milliseconds.



来源:https://stackoverflow.com/questions/15262820/run-junit-test-certain-amount-of-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!