gstackoverflow
gstackoverflow

Reputation: 36984

How to mock current date?

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

Upvotes: 3

Views: 3509

Answers (1)

assylias
assylias

Reputation: 328639

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.

Upvotes: 6

Related Questions