Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force JUnit to run one test case at a time

I have a problematic situation with some quite advanced unit tests (using PowerMock for mocking and JUnit 4.5). Without going into too much detail, the first test case of a test class will always succeed, but any following test cases in the same test class fails. However, if I select to only run test case 5 out of 10, for example, it will pass. So all tests pass when being run individually. Is there any way to force JUnit to run one test case at a time? I call JUnit from an ant-script.

I am aware of the problem of dependant test cases, but I can't pinpoint why this is. There are no saved variables across the test cases, so nothing to do at @Before annotation. That's why I'm looking for an emergency solution like forcing JUnit to run tests individually.

like image 477
Ciryon Avatar asked Feb 13 '09 08:02

Ciryon


People also ask

How do you run the same Test Case multiple times in JUnit?

The easiest (as in least amount of new code required) way to do this is to run the test as a parametrized test (annotate with an @RunWith(Parameterized. class) and add a method to provide 10 empty parameters). That way the framework will run the test 10 times.


2 Answers

I am aware of all the recommendations, but to finally answer your question here is a simple way to achieve what you want. Just put this code inside your test case:

Lock sequential = new ReentrantLock();

@Override
protected void setUp() throws Exception {
    super.setUp();
    sequential.lock();
}

@Override
protected void tearDown() throws Exception {
    sequential.unlock();
    super.tearDown();
}

With this, no test can start until the lock is acquired, and only one lock can be acquired at a time.

like image 167
hariseldon78 Avatar answered Sep 23 '22 17:09

hariseldon78


It seems that your test cases are dependent, that is: the execution of case-X affects the execution of case-Y. Such a testing system should be avoided (for instance: there's no guarantee on the order at which JUnit will run your cases).

You should refactor your cases to make them independent of each other. Many times the use of @Before and @After methods can help you untangle such dependencies.

like image 26
Itay Maman Avatar answered Sep 24 '22 17:09

Itay Maman