【发布时间】: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