无法模拟system.currenttimemillis()

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

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

  1. class MyClass{
  2. public void func1(){
  3. System.out.println("Inside func1");
  4. func2();
  5. }
  6. private void func2(){
  7. int maxWaitTime = (int)TimeUnit.MINUTES.toMillis(10);
  8. long endTime = System.currentTimeMillis() + maxWaitTime; // Mocking not happening
  9. while(System.currentTimeMillis() <= endTime) {
  10. System.out.println("Inside func2");
  11. }
  12. }
  13. }
  1. @PrepareForTest(System.class)
  2. class MyClassTest extends PowerMockTestCase{
  3. private MyClass myClass;
  4. @BeforeMethod
  5. public void setup() {
  6. MockitoAnnotations.initMocks(this);
  7. myclass = new MyClass();
  8. }
  9. @Test
  10. public void func1Test(){
  11. PowerMockito.mockStatic(System.class)
  12. PowerMockito.when(System.currentTimeMillis()).thenReturn(0L);
  13. myclass.func1();
  14. }
  15. }
rqcrx0a6

rqcrx0a61#

创建一个包构造函数,您可以在 java.time.Clock ```
class MyClass{
private Clock clock;
public MyClass() {
this.clock = Clock.systemUTC();
}
// for tests
MyClass(Clock c) {
this.clock = c;
}

  1. 然后模拟它进行测试,并使用 `this.clock.instant()` 为了得到时钟的时间
r7s23pms

r7s23pms2#

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

xt0899hw

xt0899hw3#

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

  1. <dependency>
  2. <groupId>org.mockito</groupId>
  3. <artifactId>mockito-inline</artifactId>
  4. <version>3.9.0</version>
  5. <scope>test</scope>
  6. </dependency>

请参阅以下答案,以获取有关 LocalDate 你的情况是这样的

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

注意的用法 Mockito.CALLS_REAL_METHODS 这将保证 System 如果用另一个方法调用,它将执行类的实际方法

展开查看全部

相关问题