Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test OS-specific method with JUnit?

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?

like image 202
basse Avatar asked Oct 17 '25 04:10

basse


1 Answers

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));
}
like image 113
ernest_k Avatar answered Oct 19 '25 20:10

ernest_k