How to test OS-specific method with JUnit?

≡放荡痞女 提交于 2020-01-30 08:25:33

问题


I would like to test the following method with JUnit:

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

Frankly, the only thing I've come up with is to basically copy to same logic to the test. This would, of course, protect against the method being inadvertently broken, but sounds somehow counter-intuitive.

What would be a better way to test this method?


回答1:


In your Unit tests, you can change the value of the property:

System.setProperty("os.name", "Linux")

After that, you can then test/call your systemIsWindows() method to check that what it returns using asserts.

To make it easier to set a System property and to unset that property on completion of the test (thereby facilitating test isolation, self containment) you could use either of the following JUnit add-ons:

  • JUnit4: JUnit System Rules
  • JUnit5: JUnit Extensions

For example:

@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));
}


来源:https://stackoverflow.com/questions/49872139/how-to-test-os-specific-method-with-junit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!