There is a common problem: it is difficult to scoff at time. Also, it’s really bad practice to put long running / waiting code in a unit test.
So, to create the test scheduling API, I used an interface with a real and dummy implementation like this:
public interface Clock { public long getCurrentMillis(); public void sleep(long millis) throws InterruptedException; } public static class SystemClock implements Clock { @Override public long getCurrentMillis() { return System.currentTimeMillis(); } @Override public void sleep(long millis) throws InterruptedException { Thread.sleep(millis); } } public static class MockClock implements Clock { private final AtomicLong currentTime = new AtomicLong(0); public MockClock() { this(System.currentTimeMillis()); } public MockClock(long currentTime) { this.currentTime.set(currentTime); } @Override public long getCurrentMillis() { return currentTime.addAndGet(5); } @Override public void sleep(long millis) { currentTime.addAndGet(millis); } }
In doing so, you can simulate time in your test:
@Test public void testExipres() { MockClock clock = new MockClock(); SomeCacheObject sco = new SomeCacheObject(); sco.putWithExipration("foo", 1000); clock.sleep(2000)
Of course, the advanced multi-threaded layout for Clock much more complicated, but you can do this, for example, using ThreadLocal links and a good time synchronization strategy.
Dávid Horváth Jul 02 '19 at 13:37 2019-07-02 13:37
source share