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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…