Based on this answer, I decided to implement my own MutableClock
for unit testing purposes that works slightly different:
class MutableClock extends Clock {
private final List<Instant> instants = new ArrayList<>();
public MutableClock(Instant now, TemporalAmount... amounts) {
Objects.requireNonNull(now, "now must not be null");
Objects.requireNonNull(amounts, "amounts must not be null");
instants.add(now);
for (TemporalAmount amount : amounts) {
Instant latest = instants.get(instants.size() - 1);
instants.add(latest.plus(amount));
}
}
@Override
public Instant instant() {
Instant latest = instants.get(0);
if (instants.size() > 1) {
instants.remove(0);
}
return latest;
}
...
But then I noticed I was doing this here:
instants.add(latest.plus(amount));
So, basically, I can only tick the clock "forward". Sure, that makes sense most of the time, but as all of this is for unit testing, I can imagine that I want to use such a MutableClock
instance and have it return instants that aren't always "increasing".
But when looking at the TemporalAmount interface: there is no way to express a negative amount of time?! In other words: it seems that instances of TemporalAmount
aren't "signed".
So, how could one go about this?