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

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

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

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

这个额外的样板代码并不理想。

另外,我创建了一个JUnit规则,该规则仅在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");
    }
  }

这可以通过将以下带注释的字段添加到我的测试类中来强制实现:
@Rule public WindowsOnlyRule runTestOnlyOnWindows = new WindowsOnlyRule();

在我看来,这两种机制都是不足的,因为它们会在Unix计算机上默默地通过。如果可以在执行时用类似于@Ignore的某种方式标记它们,那就更好了

有人有其他建议吗?

最佳答案

您是否考虑过假设?在before方法中,您可以执行以下操作:

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

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

07-24 09:49
查看更多