Conditionally ignoring tests in JUnit

JUnit conveniently lets you annotate a test method with @Ignore.

@Test
@Ignore
public void testAdd() {
   ...
}

This causes JUnit to completely ignore the method.

What if you want to only ignore the test under a condition determined at runtime? This would be nice:

@Test
@Ignore(someCondition())
public void testAdd() {
   ...
}

But Java and JUnit do not work like that. Instead, you need to use the Assume class.

@Test
public void testAdd() {
   Assume.assumeTrue(someCondition());
   ...
}

Voila!

Advertisements

One thought on “Conditionally ignoring tests in JUnit

  1. Pingback: The Art of Test Driven Development: Running unit tests conditionally | Gary Gregory

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s