如何使用JUnit测试特定于操作系统的方法?

bas*_*sse 1 java junit unit-testing

我想用JUnit测试以下方法:

private static boolean systemIsWindows() {
    String os = System.getProperty("os.name").toLowerCase();
    return os.startsWith("win");
}
Run Code Online (Sandbox Code Playgroud)

坦白说,我想出的唯一一件事就是基本上将相同的逻辑复制到测试中。当然,这可以防止该方法被意外破坏,但是听起来有点违反直觉。

有什么更好的方法来测试此方法?

And*_*per 7

JUnit 5 中更好的方法是使用@EnabledOnOs https://junit.org/junit5/docs/5.2.0/api/org/junit/jupiter/api/condition/EnabledOnOs.html

例如:

@Test
@EnabledOnOs({OS.WINDOWS})
public void aTest() {
    assertThat(systemIsWindows(), is(false));
}
Run Code Online (Sandbox Code Playgroud)


ern*_*t_k 5

在单元测试中,您可以更改属性的值:

System.setProperty("os.name", "Linux")
Run Code Online (Sandbox Code Playgroud)

然后,您可以测试/调用您的systemIsWindows()方法以使用断言检查其返回的内容。

为了更容易设置System属性并在测试完成时取消设置该属性(从而促进测试隔离,自我约束),可以使用以下JUnit附加组件之一:

例如:

@Test
@SystemProperty(name = "os.name", value = "Windows")
public void aTest() {
    assertThat(systemIsWindows(), is(true));
}


@Test
@SystemProperty(name = "os.name", value = "MacOs")
public void aTest() {
    assertThat(systemIsWindows(), is(false));
}
Run Code Online (Sandbox Code Playgroud)

  • 也可以使用[JUnit系统规则](https://stefanbirkner.github.io/system-rules/)(对于JUnit4)或[JUnit扩展](https://glytching.github.io/junit-extensions/systemProperty) (对于JUnit5)设置(以及在测试完成时取消设置)System属性。 (2认同)