简体   繁体   English

测试需要很长时间才能执行的方法

[英]Testing of method which takes long time to execute

Let's say I have method like this: 假设我有这样的方法:

public int toTest() {
    try { Thread.sleep(60 * 1_000); }
    catch (InterruptedException ignored) {}
    return 8;
}

And I would like to test it eg check if returned value is correct, like this: 我想测试它,例如检查返回值是否正确,如下所示:

@Test
public void test() {
    int actual = toTest();
    assertThat(actual).isEqualTo(8);
}

Is there any way to "simulate" time lapse so during test execution I will not be force to wait for whole minute? 有什么方法可以“模拟”时间流逝,因此在测试执行期间,我不会被迫等待整分钟吗?

Edit: Probably I described my question too concrete. 编辑:也许我描述我的问题太具体。 I didn't want to focus on this exact one minute but on way to bypass it. 我不想只专注于这一分钟,而是想绕过它。 There could be even 100 days but my question is if there is method to simulate this time lapse. 甚至可能有100天,但我的问题是是否有模拟此时间间隔的方法。

Like in project reactor methods with are using virtual time https://projectreactor.io/docs/test/snapshot/api/reactor/test/StepVerifier.html#withVirtualTime-java.util.function.Supplier- 就像在项目反应堆中一样,使用虚拟时间的方法https://projectreactor.io/docs/test/snapshot/api/reactor/test/StepVerifier.html#withVirtualTime-java.util.function.Supplier-

You can achieve that using Powermock. 您可以使用Powermock来实现。

// This will mock sleep method
PowerMock.mockStatic(Thread.class, methods(Thread.class, "sleep"));

PowerMockito.doThrow(new InterruptedException()).when(Thread.class);
Thread.sleep(Mockito.anyLong());

At the start of class, you will need to add this 在课程开始时,您需要添加此内容

@PrepareForTest(YourClassToWhich_ToTest_MethodBelong.class)

JUnit test the method as is (unless you add mocking..) if you want you can test internal method as toTestInternal : JUnit可以按原样测试方法(除非添加toTestInternal ..),如果您可以按toTestInternal测试内部方法:

public int toTest() {
    try { Thread.sleep(60 * 1_000); }
    catch (InterruptedException ignored) {}
    return toTestInternal();
}

public int toTestInternal() {
return 8;
}

and test the method you want ( toTestInternal ): 并测试所需的方法( toTestInternal ):

@Test
public void test() {
    int actual = toTestInternal();
    assertThat(actual).isEqualTo(8);
}

I would suggest to make the interval a dynamic parameter. 我建议将间隔设为动态参数。 It will save your time: 这样可以节省您的时间:

public int toTest(int interval) {
  try { 
      Thread.sleep(interval); 
   }catch (InterruptedException ignored) {}

  return 8;
}

and the test class to be like: 和测试类是这样的:

@Test
public void test() {
    int actual = toTest(60);
    assertThat(actual).isEqualTo(8);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM