I am working on writing JUNIT test case for my below ENUm class. My below class will only give me the hostname for the current machine where I am running my code. While I am writing JUNIT test, how can I mock the below class, so that I can change getHostName()
method whenever I want to so that whenever I am calling getDatacenter()
, it can return me whatever hostname I am passing by mocking it. I don't want to make it as a parametrized.
I just want to test certain cases while changing the hostname while mocking it.
public enum DatacenterEnum {
DEV, DC1, DC2, DC3;
public static String forCode(int code) {
return (code >= 0 && code < values().length) ? values()[code].name() : null;
}
private static final String getHostName() {
try {
return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();
} catch (UnknownHostException e) {
s_logger.logError("error = ", e);
}
return null;
}
public static String getDatacenter() {
return getHostName();
}
}
It is possible, but this is not recommended, it would be better to refactor the code.
@RunWith(PowerMockRunner.class)
@PrepareForTest(DatacenterEnum.class)
public class DatacenterEnumTest {
@Mock
InetAddress inetAddress;
@Test
public void shouldReturnDatacenter() throws UnknownHostException {
//given
mockStatic(InetAddress.class);
given(inetAddress.getCanonicalHostName()).willReturn("foo");
given(InetAddress.getLocalHost()).willReturn(inetAddress);
//when
String datacenter = DatacenterEnum.getDatacenter();
//then
assertThat(datacenter).isEqualTo("foo");
}
}