问题
In this post, I asked a small question as part of a bigger problem. Since I didn't get responses yet, I put my question here:
Is it reasonable to suppose that JUnit executes test cases sequentially: a test case ends befores the next one starts. Does it differ between JUnit versions (my priority is on JUnit4)? And if not, is there a simple way to force JUnit to execute tests sequentially?
Thank you
回答1:
Yes, by default I believe it runs tests sequentially.
JUnit 4.6 introduced an experimental ParallelRunner
to run tests in parallel - I don't know of its current status. I would expect parallelism to remain an "opt-in" feature by default though. (Judging by other answers, it looks like this is now here to stay but in a slightly different form - and still opt-in.)
回答2:
Parallel execution of tests is supported since JUnit 4.7. But as far as I know, it is never done automatically, you specifically need to configure it, e.g. like here: http://java.dzone.com/articles/running-junit-tests-parallel
But don't forget that:
Good automated tests should be independent, isolated and reproducible, making them ideal candidates for being run concurrently.
I don't know why you ask, but if the above criteria is not met, you might want to think about your test design.
回答3:
A strong and reasonable guess: yes, JUnit is single threaded by default.
Otherwise one wouldn't know if a test failed because the code is broken or it failed because of concurrency problems if some tests ran in parallel.
回答4:
Yes,
And also think of the @before
and @after
there you may have code that restores the state for the next test to run.
回答5:
Yes. As mentioned somewhere in the comments, you should plan carefully the testcase setup and teardown (all the superclasses affect those actions), as well as testsuite setup and teardown.
Also, on a secondary note, as far as I can remember, JUnit does not guarantee the order of execution of the testcases (that is, unless they are in a suite, I guess). This is important, and should push you to performing a very precise cleanup and SUT state restoration between tests, and avoid test cases relying on the results of other testcases. you might say that this is a kind of antipattern :).
回答6:
With my experience i can say we can serialize tests in a class by naming the method name having Test in it. ex:
@Test
public ..... firstTest ()
{
}
@Test
public .... thirdTest()
{
}
@Test
public....secondTest()
{
}
The order is firstTest,thirdTest,secondTest
来源:https://stackoverflow.com/questions/7267790/does-junit-execute-test-cases-sequentially