Sunday, October 5, 2008

How to skip a test with JUnit

In my past, about 10 years, ago, I've been a very committed Perl programmer. This meant, in particular, that I have written my share of test cases. One of the nicer features of the testing framework is the possibility to skip tests at runtime. One can use this for all kind of things like suppressing slower tests in every days work, for restricting tests to certain operating systems, and so on. The test suite runner recognizes skipped tests and reports them as skipped (as opposed to failed, or successfull).

On the other hand, I have always missed this feature in JUnit. But, from what I can tell, it's finally there in JUnit 4.4. Suggest the following example, which runs a test only, if the system property "run.slow.tests" is set.


import static org.junit.Assume.*;

public class ConditionalTest {
@Test fastTest() { // Performed always
...
}

@Test slowTest() { // Performed always
assumeTrue(Boolean.getBoolean("run.slow.tests"));
...
}
}


Internally, the feature works by throwing an AssumptionViolationException.