仅在 Windows 上运行单元测试



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

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

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

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

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

或者,我创建了一个仅在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");
    }
  }

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

@Rule public WindowsOnlyRule runTestOnlyOnWindows = new WindowsOnlyRule();

在我看来,这两种机制都有缺陷,因为在Unix机器上它们会默默地通过。 如果可以在执行时以某种方式标记它们,效果类似于@Ignore

有人有其他建议吗?

在 Junit5 中,有用于配置或运行特定操作系统测试的选项。

@EnabledOnOs({ LINUX, MAC })
void onLinuxOrMac() {
}
@DisabledOnOs(WINDOWS)
void notOnWindows() {
    // ...
}

你研究过假设吗? 在前面的方法中,您可以执行此操作:

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

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

你看过 JUnit 假设吗?

用于陈述有关测试条件的假设 是有意义的。失败的假设并不意味着代码被破坏, 但该测试没有提供任何有用的信息。默认的 JUnit 运行器将假设失败的测试视为忽略

(这似乎符合您忽略这些测试的标准(。

如果你使用 Apache Commons Lang 的 SystemUtils:在 @Before 方法或不想在 Win上运行的测试中,可以添加:

Assume.assumeTrue(SystemUtils.IS_OS_WINDOWS);

大概你不需要在 junit 测试中实际调用 Windows API;你只关心作为单元测试目标的类调用它认为是 Windows API 的东西。

考虑将 Windows API 调用模拟为单元测试的一部分。

最新更新