【问题标题】:Run unit tests only on Windows仅在 Windows 上运行单元测试
【发布时间】:2014-05-01 15:21:12
【问题描述】:

我有一个通过 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 的方式标记它们会更好

有人有其他建议吗?

【问题讨论】:

    标签: java junit junit-rule


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您使用新的 junit 功能进行更新,很高兴知道。
    【解决方案2】:

    您是否研究过假设?在之前的方法中,您可以这样做:

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

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

    【讨论】:

    • 这正是我正在寻找的功能。谢谢。
    【解决方案3】:

    你看过 JUnit assumptions 吗?

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

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

    【讨论】:

    • @BrianAgnew 使用 TestRules 是我在问题中已经描述的第二种机制。我会看看假设。
    • 我认为在这种情况下可能更合适
    • @BrianAgnew 对不起,我有点脾气暴躁。我只是想我看到你编辑了假设部分。
    • 没问题。这是一个快速发展的网站!
    【解决方案4】:

    如果您使用 Apache Commons Lang 的 SystemUtils,您可以在 @Before 方法中添加:

    Assume.assumeTrue(SystemUtils.IS_OS_WINDOWS);
    

    【讨论】:

      【解决方案5】:

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

      考虑将模拟 windows api 调用作为单元测试的一部分。

      【讨论】:

      • 我怀疑他需要在某个阶段调用 Windows 代码,因此需要进行 Windows 兼容测试。我同意你的观点。虽然嘲笑,但我敢肯定它会在某处使用
      • 是的,我确实考虑过模拟,但在这种情况下,我确实想调用底层的 impl
      猜你喜欢
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      • 1970-01-01
      • 2012-11-28
      相关资源
      最近更新 更多