Mock java.time.format.DateTimeFormatter class

后端 未结 2 1457
花落未央
花落未央 2020-12-12 04:17

I\'m trying to mock the DateTimeFormatter class. I\'ve done the following:

@RunWith(PowerMockRunner.class)
@PrepareForTest({DateTimeFormatter.class})
public          


        
2条回答
  •  醉话见心
    2020-12-12 05:08

    An alternative to mocking LocalDateTime.now() is to inject the clock into your class and change your (or add another) constructor like this:

    AwesomeClass(DateTimeFormatter fmt, Clock clock) {
      //instead of LocalDateTime now = LocalDateTime.now():
      LocalDateTime now = LocalDateTime.now(clock);
    }
    

    Then in your test:

    new AwesomeClass(formatter, Clock.fixed(the time you want here));
    

提交回复
热议问题