Using JUnit’s “Assume” for faster tests

Using JUnit’s “Assume” for faster tests

I wanted to share something I learned today about JUnit. Some of you may know this, but it was news to me.

My triggering problem was that I was writing some unit-tests which required OSGi to be started up. All my other tests were plain (i.e. non-OSGi) tests. Since I didn’t want to suffer from the startup delay every time I ran the unit tests, I thought about “ignoring” these OSGi dependent tests based on whether I was running plain tests or PDE tests. A bit of googling turned up an interesting feature of JUnit (since 4.4): Assumptions. Assumptions are defined in the Assume class and are basically the exact opposite of JUnit assertions: If an assumption fails, the test automatically passes. This keeps tests from failing when certain preconditions have not been met. Ideally these would be marked as “ignored” or “skipped” but still better than nothing (maybe someone with commit rights to the TestRunner could make this happen).

This neat feature allows us to do the following:

  public void setUp() {
    Assume.assumeTrue( Activator.isOsgiRunning() );

Now the tests will only be executed if they are running in an OSGi environment.

If you put this in an abstract base class that all PDE Tests inherit, these will be ignored when running in “plain” mode, for even quicker test runs. In that case be sure to name your @Before method in a unique way so it does not get overridden (and thus nullified) by subclasses.

These assumptions might also be useful for tests known to fail on particular platforms, JREs, runtime environments etc. Another neat addition to my toolbox. The bit of hair in this soup is that JUnit 4 support in Eclipse is a bit lacking, especially when it comes to the PDE build. Some of this is detailed in Bug #153429 which hopefully will be fixed in 3.6. (Hint: Vote!)

1 Comment
  • Jordan
    Posted at 7:30 pm, October 7, 2009

    Basically, it’s dependent testing, which the JUnit team has always said should never be done (and which TestNG has had for years).