Reputation: 3
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 e.g. 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-
Upvotes: 0
Views: 515
Reputation: 3841
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);
}
Upvotes: 0
Reputation: 4587
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)
Upvotes: 1
Reputation: 58772
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);
}
Upvotes: 0