'PowerMockito mocked static method is calling actual class method instead of mocked class
I have a function which calls a static function in java (TimeZone.getDefault()) UnitProperty.java
public String getDeviceTimeZone() {
return TimeZone.getDefault().getID();
}
I am trying to write unit test for this (UnitPropertyTest.java)
import...
@RunWith(PowerMockRunner.class)
@PrepareForTest(TimeZone.class)
public class UnitPropertyTest {
@InjectMocks
private UnitProperty unitProperty;
@Before
public void setup(){
PowerMockito.mockStatic(TimeZone.class);
unitProperty = new UnitProperty();
}
@Test
public void test_getDeviceTimeZone_returns_set_time_zone() throws Exception {
String expectedTimeZone = "mock-time-zone-value";
when(TimeZone.getDefault().getID()).thenReturn(expectedTimeZone);
System.out.println("Mocked Time Zone: " + TimeZone.getDefault().getID());
assertEquals(expectedTimeZone, unitProperty.getDeviceTimeZone());
}
}
But the test fails because:
Mocked Time Zone: mock-time-zone-value
Expected :mock-time-zone-value
Actual :Europe/London
I am not sure why unitProperty.getDeviceTimeZone() isn't using mocked TimeZone class but instead calling the actual TimeZone's method value?
I have been searching for a while. Can anyone help me in understanding this behavior? Why isn't method in mocked class getting called?
Thanks in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
