首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法模拟System.currentTimeMillis()

无法模拟System.currentTimeMillis()
EN

Stack Overflow用户
提问于 2021-04-25 21:07:52
回答 3查看 277关注 0票数 1

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

代码语言:javascript
运行
复制
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");
        }
    }
}
代码语言:javascript
运行
复制
@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();
   }
}
EN

回答 3

Stack Overflow用户

发布于 2021-04-25 21:51:56

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

代码语言:javascript
运行
复制
class MyClass{ 
    private Clock clock;
    public MyClass() {
        this.clock = Clock.systemUTC();
    } 
    // for tests 
    MyClass(Clock c) {
        this.clock = c;
   } 

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

票数 4
EN

Stack Overflow用户

发布于 2021-04-25 21:47:03

您需要向类MyClassTest添加注释@RunWith(PowerMockRunner.class)

然而,我建议重构代码以使用java.time.Clock,而不是mocking。

票数 0
EN

Stack Overflow用户

发布于 2021-04-25 21:50:39

您可以使用同样具有mockStatic方法的Mockito,而不使用PowerMock

代码语言:javascript
运行
复制
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <version>3.9.0</version>
    <scope>test</scope>
</dependency>

有关LocalDate的示例,请参见this answer

下面是它在您的例子中的样子

代码语言:javascript
运行
复制
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时,它都会执行类的实际方法

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67253755

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档