Run unit tests on Windows only

I have a class that calls native Windows API calls through JNA. How can I write JUnit tests that will run on a Windows development machine, but will be ignored on a Unix build server?

I can easily get the main OS using System.getProperty("os.name")

I can write protection blocks in my tests:

 @Test public void testSomeWindowsAPICall() throws Exception { if (isWindows()) { // do tests... } } 

This additional boiler plate code is not ideal.

As an alternative, I created a JUnit rule that runs only a test method on Windows:

  public class WindowsOnlyRule implements TestRule { @Override public Statement apply(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { if (isWindows()) { base.evaluate(); } } }; } private boolean isWindows() { return System.getProperty("os.name").startsWith("Windows"); } } 

And this can be accomplished by adding this annotated field to my test class:

 @Rule public WindowsOnlyRule runTestOnlyOnWindows = new WindowsOnlyRule(); 

Both of these mechanisms, in my opinion, are insufficient in that they will pass silently on a Unix machine. It would be better if they could be marked somehow at runtime with something similar to @Ignore

Does anyone have an alternative suggestion?

+7
java junit junit-rule
source share
3 answers

Have you studied the assumptions? In the before method, you can do this:

 @Before public void windowsOnly() { org.junit.Assume.assumeTrue(isWindows()); } 

Documentation: http://junit.sourceforge.net/javadoc/org/junit/Assume.html

+12
source share

Have you looked at JUnit assumptions ?

useful for formulating assumptions about the conditions in which the test makes sense. An unsuccessful assumption does not mean that the code is broken, but that the test does not provide any useful information. By default, the JUnit runner treats tests with failed assumptions as ignored.

(which seems to fit your criteria for ignoring these tests).

+2
source share

Presumably, you do not need to actually invoke the Windows API as part of the junit test; you don't care that the class that is the object of the unit test call invokes what it considers the Windows API.

Consider the mockery of windows api calls as part of unit tests.

0
source share

All Articles