Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run unit tests only on Windows

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

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

I can write guard blocks in my tests:

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

This extra boiler plate code is not ideal.

Alternatively I have created a JUnit rule that only runs the 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 enforced by adding this annotated field to my test class:

@Rule public WindowsOnlyRule runTestOnlyOnWindows = new WindowsOnlyRule();

Both these mechanisms are deficient in my opinion in that on a Unix machine they will silently pass. It would be nicer if they could be marked somehow at execution time with something similar to @Ignore

Does anybody have an alternative suggestion?

like image 325
darrenmc Avatar asked May 01 '14 15:05

darrenmc


People also ask

Are unit tests run locally?

Unit tests should run on your local machine AND on the build server. They are an invaluable resource as feedback for the developer. The DEV should write the unit tests. Before checking in, he should run the unit tests to make sure he does not break anything.

How do I run a unit test in Visual Studio?

Run tests in Test Explorer If Test Explorer is not visible, choose Test on the Visual Studio menu, choose Windows, and then choose Test Explorer (or press Ctrl + E, T). As you run, write, and rerun your tests, the Test Explorer displays the results in a default grouping of Project, Namespace, and Class.


1 Answers

In Junit5, There are options for configuring or run the test for specific Operating System.

@EnabledOnOs({ LINUX, MAC })
void onLinuxOrMac() {

}

@DisabledOnOs(WINDOWS)
void notOnWindows() {
    // ...
}
like image 78
Rakesh Chaudhari Avatar answered Oct 02 '22 22:10

Rakesh Chaudhari