For some testing purposes I would like to predict exactly what System.currentTimeMillis()
will return. Is there any way in which I can freeze or manually set what w
Yes, it is possible, but it is a test code smell.
You can use a mocking library which enables you to mock static methods (as in this PowerMock example), but you should avoid doing this, and encapsulate the time data as the other answers suggest.
This is how the test would look like, using PowerMock and Mockito:
@RunWith(PowerMockRunner.class)
@PrepareForTest(System.class)
public class TestTime {
@Test
public void testTime() {
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.currentTimeMillis()).thenReturn(42l);
System.out.println(System.currentTimeMillis()); //prints 42
//your test code here
}
}