我正在使用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();
}
}
发布于 2021-04-25 21:51:56
创建一个可以在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()
获取时钟时间
发布于 2021-04-25 21:47:03
您需要向类MyClassTest
添加注释@RunWith(PowerMockRunner.class)
。
然而,我建议重构代码以使用java.time.Clock
,而不是mocking。
发布于 2021-04-25 21:50:39
您可以使用同样具有mockStatic
方法的Mockito
,而不使用PowerMock
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.9.0</version>
<scope>test</scope>
</dependency>
有关LocalDate
的示例,请参见this answer
下面是它在您的例子中的样子
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
时,它都会执行类的实际方法
https://stackoverflow.com/questions/67253755
复制相似问题