我有一个类,通过JNA调用本地 Windows API。如何编写 JUnit 测试,在 Windows 开发机上执行但在 Unix 构建服务器上被忽略?
我可以使用 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
的方式标记它们,那将会更好。
是否有其他替代建议?