How to mock current date?

落花浮王杯 提交于 2019-12-12 16:48:25

问题


I have a method in my code which verifies that current day is business. it checks database calendar for this.

method looks like this:

public boolean iBusinessDayToday() {
      LocalDate today = LocalDate.now();
      //logic with today
}

I need to write unit tests for this.

I want that unit test doesn't depends in week day.

What do you think need this issue to use powerMockito to mock LocalDate.now() ?


回答1:


An alternative would be to pass the clock to the method:

public boolean iBusinessDayToday() {
  return iBusinessDayToday(Clock.systemDefaultZone());
}

@VisibleForTesting
boolean iBusinessDayToday(Clock clock) {
      LocalDate today = LocalDate.now(clock);
      //logic with today
}

Now you can test the second method and pass a a fixed clock - no need to use a mocking framework.



来源:https://stackoverflow.com/questions/35774492/how-to-mock-current-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!