仅在Windows上运行单元测试

dar*_*nmc 13 java junit junit-rule

我有一个通过JNA进行本机Windows API调用的类.如何编写将在Windows开发机器上执行但在Unix构建服务器上将被忽略的JUnit测试?

我可以轻松地使用主机操作系统 System.getProperty("os.name")

我可以在测试中编写保护块:

@Test public void testSomeWindowsAPICall() throws Exception {
  if (isWindows()) {
    // do tests...
  }
}
Run Code Online (Sandbox Code Playgroud)

这个额外的锅炉板代码并不理想.

或者,我创建了一个只在Windows上运行测试方法的JUnit规则:

  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");
    }
  }
Run Code Online (Sandbox Code Playgroud)

这可以通过将这个带注释的字段添加到我的测试类来强制执行:

@Rule public WindowsOnlyRule runTestOnlyOnWindows = new WindowsOnlyRule();
Run Code Online (Sandbox Code Playgroud)

这两种机制在我看来都是不足的,因为在Unix机器上它们会默默地传递.如果它们可以在执行时以某种方式用类似的东西标记它会更好@Ignore

有人有其他建议吗?

jgi*_*ter 19

你有没有考虑过假设?在before方法中,您可以这样做:

@Before
public void windowsOnly() {
    org.junit.Assume.assumeTrue(isWindows());
}
Run Code Online (Sandbox Code Playgroud)

文档:http://junit.sourceforge.net/javadoc/org/junit/Assume.html


Rak*_*ari 11

在Junit5中,可以选择为特定操作系统配置或运行测试.

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

}

@DisabledOnOs(WINDOWS)
void notOnWindows() {
    // ...
}
Run Code Online (Sandbox Code Playgroud)