Merge branch 'sanketmeghani-master'

This commit is contained in:
Zeger Hendrikse 2016-10-10 18:29:56 +02:00
commit 9ec0893cdd
1 changed files with 26 additions and 16 deletions

View File

@ -1,47 +1,57 @@
package com.baeldung.util; package com.baeldung.util;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.time.Clock;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalTime; import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.ChronoField; import java.time.temporal.ChronoField;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.mockito.Mockito;
public class CurrentDateTimeTest { public class CurrentDateTimeTest {
private static Clock clock;
@BeforeClass
public static void setup() {
final Instant currentTime = Instant.parse("2016-10-09T15:10:30.00Z");
clock = Mockito.mock(Clock.class);
when(clock.instant()).thenAnswer((invocation) -> currentTime);
when(clock.getZone()).thenAnswer((invocation) -> ZoneId.of("UTC"));
}
@Test @Test
public void shouldReturnCurrentDate() { public void shouldReturnCurrentDate() {
final LocalDate now = LocalDate.now(); final LocalDate now = LocalDate.now(clock);
final Calendar calendar = GregorianCalendar.getInstance();
assertEquals("10-10-2010".length(), now.toString().length()); assertEquals(9, now.get(ChronoField.DAY_OF_MONTH));
assertEquals(calendar.get(Calendar.DATE), now.get(ChronoField.DAY_OF_MONTH)); assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR));
assertEquals(calendar.get(Calendar.MONTH), now.get(ChronoField.MONTH_OF_YEAR) - 1); assertEquals(2016, now.get(ChronoField.YEAR));
assertEquals(calendar.get(Calendar.YEAR), now.get(ChronoField.YEAR));
} }
@Test @Test
public void shouldReturnCurrentTime() { public void shouldReturnCurrentTime() {
final LocalTime now = LocalTime.now(); final LocalTime now = LocalTime.now(clock);
final Calendar calendar = GregorianCalendar.getInstance();
assertEquals(calendar.get(Calendar.HOUR_OF_DAY), now.get(ChronoField.HOUR_OF_DAY)); assertEquals(15, now.get(ChronoField.HOUR_OF_DAY));
assertEquals(calendar.get(Calendar.MINUTE), now.get(ChronoField.MINUTE_OF_HOUR)); assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR));
assertEquals(calendar.get(Calendar.SECOND), now.get(ChronoField.SECOND_OF_MINUTE)); assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE));
} }
@Test @Test
public void shouldReturnCurrentTimestamp() { public void shouldReturnCurrentTimestamp() {
final Instant now = Instant.now(); final Instant now = Instant.now(clock);
final Calendar calendar = GregorianCalendar.getInstance();
assertEquals(calendar.getTimeInMillis() / 1000, now.getEpochSecond()); assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
} }
} }