无法模拟System.currentTimeMillis()



我正在使用TestNG编写单元测试。问题是,当我模拟System.currentTimeMillis时,它会返回实际值,而不是模拟的值。理想情况下,它应该返回0L,但它返回实际值。我该怎么做才能继续?

class MyClass{
public void func1(){
System.out.println("Inside func1");
func2();
}
private void func2(){
int maxWaitTime = (int)TimeUnit.MINUTES.toMillis(10);
long endTime = System.currentTimeMillis() + maxWaitTime; // Mocking not happening
while(System.currentTimeMillis() <= endTime) {
System.out.println("Inside func2");
}
}
}
@PrepareForTest(System.class)
class MyClassTest extends PowerMockTestCase{
private MyClass myClass;

@BeforeMethod
public void setup() {
MockitoAnnotations.initMocks(this);
myclass = new MyClass();
}
@Test    
public void func1Test(){
PowerMockito.mockStatic(System.class)
PowerMockito.when(System.currentTimeMillis()).thenReturn(0L);
myclass.func1();
}
}

制作一个可以在java.time.Clock中传递的包构造函数

class MyClass{ 
private Clock clock;
public MyClass() {
this.clock = Clock.systemUTC();
} 
// for tests 
MyClass(Clock c) {
this.clock = c;
} 

然后模拟它进行测试,并使用this.clock.instant()获得时钟的时间

您需要将注释@RunWith(PowerMockRunner.class)添加到类MyClassTest中。

尽管如此,我还是建议重构代码以使用java.time.Clock,而不是嘲讽。

您可以使用Mockito,而不是使用PowerMock,它也有mockStatic方法

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.9.0</version>
<scope>test</scope>
</dependency>

有关LocalDate的示例,请参见此答案

以下是在您的情况下的情况

try(MockedStatic<System> mock = Mockito.mockStatic(System.class, Mockito.CALLS_REAL_METHODS)) {
doReturn(0L).when(mock).currentTimeMillis();
// Put the execution of the test inside of the try, otherwise it won't work
}

注意Mockito.CALLS_REAL_METHODS的用法,它将保证无论何时用另一个方法调用System,它都将执行类的真实方法

相关内容

  • 没有找到相关文章

最新更新