javajmockit

Mock a public static method with different return values


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?


Solution

  • 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;
    }};