Joda-Time library provides us a Virtual Clock utility named "DateTimeUtils". This is a demonstration for mocking start-end times.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.joda.time.DateTime; | |
public class StartEndTimeWithJodaTime { | |
private DateTime startTime; | |
private DateTime endTime; | |
public void process() { | |
startTime = DateTime.now(); | |
// some heavy processing | |
System.out.println("Processing..."); | |
endTime = DateTime.now(); | |
} | |
public DateTime getStartTime() { | |
return startTime; | |
} | |
public DateTime getEndTime() { | |
return endTime; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.joda.time.DateTime; | |
import org.joda.time.DateTimeUtils; | |
import org.junit.After; | |
import org.junit.Test; | |
import static org.hamcrest.Matchers.equalTo; | |
import static org.junit.Assert.assertThat; | |
import static org.mockito.Mockito.mock; | |
import static org.mockito.Mockito.when; | |
public class StartEndTimeWithJodaTimeTest { | |
@Test | |
public void saveStartEndTimeOfProcessing() { | |
final DateTime now = new DateTime(1989, 7, 4, 1, 15); | |
final DateTime fiveMinutesLater = now.plusMinutes(5); | |
// We need mock millis provider, because we need to return different times for each DateTime.now() calls | |
DateTimeUtils.MillisProvider mockMillisProvider = mock(DateTimeUtils.MillisProvider.class); | |
when(mockMillisProvider.getMillis()).thenReturn(now.getMillis()).thenReturn(fiveMinutesLater.getMillis()); | |
DateTimeUtils.setCurrentMillisProvider(mockMillisProvider); | |
StartEndTimeWithJodaTime processor = new StartEndTimeWithJodaTime(); | |
processor.process(); | |
assertThat(processor.getStartTime(), equalTo(now)); | |
assertThat(processor.getEndTime(), equalTo(fiveMinutesLater)); | |
} | |
@After | |
public void after() { | |
// Use this to reset mock millis provider to system millis provider | |
DateTimeUtils.setCurrentMillisSystem(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment