3

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() ?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
  • Can you change the code, e.g. in `iBusinessDayToday()`? – user140547 Mar 03 '16 at 14:13
  • 1
    As the Javadoc of `LocalDate.now()` warns: `Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.` – biziclop Mar 03 '16 at 14:21

1 Answers1

6

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • 2
    It might be better to make the `Clock` a member of the class, passed to its constructor. Or to change the method to `isBusinessDay(LocalDate day)`. The question is what class is responsible for defining "today"? That's the class which should own the `Clock`. – aro_tech Mar 04 '16 at 05:00