Is it possible to freeze System.currentTimeMillis() for testing

前端 未结 6 2535
孤街浪徒
孤街浪徒 2021-02-20 02:24

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

6条回答
  •  醉梦人生
    2021-02-20 02:58

    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
        }
    
    }
    

提交回复
热议问题