Stefan M.
3 min readFeb 18, 2016

--

System.currentTimeMillis()
@Test
public void testCurrentTimeMillis_ShouldReturnCurrentTimeMillis() throws Exception {
long expectedTime = System.currentTimeMillis();

long clockTime = mMyClock.currentTimeMillis();

assertThat(expectedTime, is(equalTo(clockTime)));
}
java.lang.AssertionError: 
Expected: is <1455569450334L>
but: was <1455569450336L>
@VisibleForTesting
long currentTimeMillis() {
return System.currentTimeMillis();
}
private long mTimeMillis = System.currentTimeMillis();

@Before
public void setUp() throws Exception {
mMyClock = new MyClock() {
long currentTimeMillis() {
return mTimeMillis;
}
};
}
@Test
public void testCurrentTimeMillis_ShouldReturnCurrentTimeMillis() throws Exception {
long clockTime = mMyClock.currentTimeMillis();

assertThat(mTimeMillis, is(equalTo(clockTime)));
}
@Test
public void testGetCurrentName_ShouldReturnTimeInGermanFormat() throws Exception {
String germanTime = mMyClock.getCurrentTime(TimeFormat.GERMAN);

assertThat(germanTime, is(equalTo("14:45 Uhr")));
}
@Test
public void testGetCurrentName_ShouldReturnTimeInGermanFormat() throws Exception {
String germanTime = mMyClock.getCurrentTime(TimeFormat.GERMAN);

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm 'Uhr'");
String formattedTime = simpleDateFormat.format(new Date(mTimeMillis));
assertThat(germanTime, is(equalTo(formattedTime)));
}
java.lang.AssertionError: 
Expected: is “18:50 Uhr”
but: was “14:45 Uhr”
public String getCurrentTime(TimeFormat format) {
switch (format) {
case GERMAN:
return getStringFormattedTimeWithPatternAndLocale("HH:mm 'Uhr'", Locale.GERMANY);
case AMERICAN:
return "2:45 PM";
case GERMAN_WITH_DATE:
return "14:45 Uhr, Freitag 12.02.2016";
case AMERICAN_WITH_DATE:
return "2:45 PM, Friday 02.12.2016";
default:
return "";
}
}
@VisibleForTesting
long currentTimeMillis() {
return System.currentTimeMillis();
}
private String getStringFormattedTimeWithPatternAndLocale(String pattern, Locale locale) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, locale);
Date currentDate = new Date(currentTimeMillis());
return simpleDateFormat.format(currentDate);
}
MyClock clock = new MyClock();

String currentTimeInGermanFormat = clock.getCurrentTime(TimeFormat.GERMAN);
System.out.println(currentTimeInGermanFormat);

String currentTimeInAmericanFormat = clock.getCurrentTime(TimeFormat.AMERICAN);
System.out.println(currentTimeInAmericanFormat);

String currentTimeInGermanFormatAndDate = clock.getCurrentTime(TimeFormat.GERMAN_WITH_DATE);
System.out.println(currentTimeInGermanFormatAndDate);

String currentTimeInAmericanFormatAndDate = clock.getCurrentTime(TimeFormat.AMERICAN_WITH_DATE);
System.out.println(currentTimeInAmericanFormatAndDate);
// Output: (actually ;))
// 19:35 Uhr
// 07:35 PM
// 19:35 Uhr, Donnerstag 18.02.2016
// 07:35 PM, Thursday 02.18.2016

--

--