Monday, January 4, 2010

JUnit Assumptions

This is a new feature I just learned about. JUnit has a class called Assume which allows you to make assumptions about the environment you're running in. If the assumption is not true, then the test is ignored (that is the default test runner's behavior).
For example, sometimes I have tests that are operating system specific and don't necessarily make sense on other operating systems. Typically, I would do something like:

@Test
public void windowsSpecificTest() {
if ( System.getProperty("os.name").toLowerCase().contains("win") ) {
// do windows test
}
else {
LOGGER.warn("Test skipped because not on windows");
}
}

With the Assume class, you could do something like:

@Test
public void windowsSpecificTest() {
Assume.assumeTrue(System.getProperty("os.name").toLowerCase().contains("win"));
// do windows test. if this is windows, the test will be ignored.
}


This isn't earth shattering, but it's another nifty little trick.

1 comment: