PowerMockito:尝试模拟系统 class 方法或任何其他最终 class 方法
PowerMockito: Trying to mock System class methods or any other Final class method
我正在尝试模拟系统 class 以获得 currentTimeMillis() 的常量值。
因为我不能使用 Mockito 来模拟最终 classes 我使用的是 PowerMock,但是当模拟 System.currentTimeMillis() 我得到错误 "Cannot resolve method when(long)".
我的代码如下所示:
PowerMockito.mockStatic(System.class);
when(System.currentTimeMillis()).thenReturn(CURRENT_TIME_STAMP);
我也将我的 class 注释为:
@RunWith(PowerMockRunner.class)
@PrepareForTest(System.class)
public class DateTimeUtilsTest {
已解决。
应该是
PowerMockito.when(System.currentTimeMillis()).thenReturn(CURRENT_TIME_STAMP);
或者像
一样静态导入 PowerMockito
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
同样,可以模拟任何系统 class 方法或可以模拟任何其他最终 class。
这就是为什么你应该先写测试,然后才不要写不可测试的代码。
你的代码不应该直接访问瞬态静态,而是通过一个你可以模拟的组件。
我正在尝试模拟系统 class 以获得 currentTimeMillis() 的常量值。 因为我不能使用 Mockito 来模拟最终 classes 我使用的是 PowerMock,但是当模拟 System.currentTimeMillis() 我得到错误 "Cannot resolve method when(long)".
我的代码如下所示:
PowerMockito.mockStatic(System.class);
when(System.currentTimeMillis()).thenReturn(CURRENT_TIME_STAMP);
我也将我的 class 注释为:
@RunWith(PowerMockRunner.class)
@PrepareForTest(System.class)
public class DateTimeUtilsTest {
已解决。
应该是
PowerMockito.when(System.currentTimeMillis()).thenReturn(CURRENT_TIME_STAMP);
或者像
一样静态导入 PowerMockitoimport static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
同样,可以模拟任何系统 class 方法或可以模拟任何其他最终 class。
这就是为什么你应该先写测试,然后才不要写不可测试的代码。
你的代码不应该直接访问瞬态静态,而是通过一个你可以模拟的组件。