Conditionally ignoring tests in JUnit 4
The JUnit way is to do this at run-time is org.junit.Assume
.
@Before
public void beforeMethod() {
org.junit.Assume.assumeTrue(someCondition());
// rest of setup.
}
You can do it in a @Before
method or in the test itself, but not in an @After
method. If you do it in the test itself, your @Before
method will get run. You can also do it within @BeforeClass
to prevent class initialization.
An assumption failure causes the test to be ignored.
Edit: To compare with the @RunIf
annotation from junit-ext, their sample code would look like this:
@Test
public void calculateTotalSalary() {
assumeThat(Database.connect(), is(notNull()));
//test code below.
}
Not to mention that it is much easier to capture and use the connection from the Database.connect()
method this way.
You should checkout Junit-ext
project. They have RunIf
annotation that performs conditional tests, like:
@Test
@RunIf(DatabaseIsConnected.class)
public void calculateTotalSalary() {
//your code there
}
class DatabaseIsConnected implements Checker {
public boolean satisify() {
return Database.connect() != null;
}
}
[Code sample taken from their tutorial]