Mocking time in Java 8's java.time API

后端 未结 8 1696
我寻月下人不归
我寻月下人不归 2020-11-27 16:09

Joda Time has a nice DateTimeUtils.setCurrentMillisFixed() to mock time.

It\'s very practical in tests.

Is there an equivalent in Java 8\'s java.time API

8条回答
  •  星月不相逢
    2020-11-27 16:51

    I find using Clock clutters your production code.

    You can use JMockit or PowerMock to mock static method invocations in your test code. Example with JMockit:

    @Test
    public void testSth() {
      LocalDate today = LocalDate.of(2000, 6, 1);
    
      new Expectations(LocalDate.class) {{
          LocalDate.now(); result = today;
      }};
    
      Assert.assertEquals(LocalDate.now(), today);
    }
    

    EDIT: After reading the comments on Jon Skeet's answer to a similar question here on SO I disagree with my past self. More than anything else the argument convinced me that you cannot parallize tests when you mock static methods.

    You can/must still use static mocking if you have to deal with legacy code, though.

提交回复
热议问题