1

This code is supposed to check if an hour has passed and then perform a specific action. To mimic this, I'm mocking the ZonedDateTime class in JMockit and want it's now method (ZonedDateTime.now(ZoneOffset.UTC);) to return two different values during the execution of my code. My first attempt involved the following mocked implementation of a static method:

ZonedDateTime instantExpected = ZonedDateTime.now(ZoneOffset.UTC);
new Expectations(ZonedDateTime.class) {{
    ZonedDateTime.now(ZoneOffset.UTC);
    result = instantExpected;
}};

The above code ensures that the same instant gets returned every time the function is called, but it does not allow me to change the value after a certain number of function calls. I want something similar to how the below code should work.

ZonedDateTime instantExpected = ZonedDateTime.now(ZoneOffset.UTC);
new Expectations(ZonedDateTime.class) {{
    ZonedDateTime.now(ZoneOffset.UTC);
    result = instantExpected;
    times = 2; // the first two times it should return this value for "now"

    ZonedDateTime.now(ZoneOffset.UTC);
    result = instantExpected.plusHours(1L);
    times = 1; // the third time it should return this new value for "now"
}};

How can I mock a public static method and have it return different values for the same function?

  • 2
    a better alternative is to pass in a clock to methods that get the time. The clock has a stub implementaron called FixedClock that can be injected. See https://stackoverflow.com/a/51525990/217324 – Nathan Hughes Aug 06 '21 at 15:57
  • Thanks for the note. For future reference here's a link for mocking the clock in Java as you described: https://stackoverflow.com/questions/32792000/how-can-i-mock-java-time-localdate-now#32794740 – Andrew Mascillaro Aug 06 '21 at 16:02

1 Answers1

0

Returning a list of times as a result in the Expectations block did the job.

ZonedDateTime instantExpected = ZonedDateTime.now(ZoneOffset.UTC);
ZonedDateTime secondInstant = instantExpected.plusHours(1L);
List<ZonedDateTime> allTimes = new ArrayList<ZonedDateTime>();
allTimes.add(instantExpected);
allTimes.add(instantExpected);
allTimes.add(secondInstant);
new Expectations(ZonedDateTime.class) {{
    ZonedDateTime.now(ZoneOffset.UTC);
    result = allTimes;
}};