简体   繁体   中英

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.

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-

You can achieve that using 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 :

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 ):

@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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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