无法模拟system.currenttimemillis()

tuwxkamq  于 2021-07-13  发布在  Java
关注(0)|答案(3)|浏览(455)

我正在使用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();
   }
}
rqcrx0a6

rqcrx0a61#

创建一个包构造函数,您可以在 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()` 为了得到时钟的时间
r7s23pms

r7s23pms2#

您需要添加注解 @RunWith(PowerMockRunner.class) 去上课 MyClassTest .
尽管如此,我还是建议重构代码以使用 java.time.Clock ,而不是嘲笑。

xt0899hw

xt0899hw3#

而不是使用 PowerMock ,您可以使用 Mockito 它也有一个 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 如果用另一个方法调用,它将执行类的实际方法

相关问题