Skip to content

Commit

Permalink
added tests for DateCodec
Browse files Browse the repository at this point in the history
  • Loading branch information
flaminiaScarciofolo committed Oct 23, 2024
1 parent 0f787ba commit 8b660c1
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package it.pagopa.selfcare.user.conf;

import org.bson.BsonReader;
import org.bson.BsonWriter;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;
import org.bson.json.JsonReader;
import org.bson.json.JsonWriter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.io.StringWriter;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

import static org.junit.jupiter.api.Assertions.*;

class DateCodecTest {

private final DateCodec dateCodec = new DateCodec();

@Test
void decode_withValidDateTime_shouldReturnOffsetDateTime() {
LocalDateTime localDateTime = LocalDateTime.of(2021, 12, 1, 0, 0, 0);
String epoch = String.valueOf(localDateTime.toInstant(ZoneOffset.UTC).toEpochMilli());
BsonReader reader = new JsonReader("{\"date\": {\"$date\":" + epoch + "}}");
reader.readStartDocument();
reader.readName("date");

OffsetDateTime result = dateCodec.decode(reader, DecoderContext.builder().build());

OffsetDateTime expected = OffsetDateTime.of(2021, 12, 1, 0, 0, 0, 0, ZoneOffset.UTC);
OffsetDateTime desiredOffsetDateTime = expected.withOffsetSameInstant(ZoneOffset.of("+01:00"));

assertEquals(desiredOffsetDateTime, result);
}

@Test
void decode_withInvalidType_shouldReturnNull() {
BsonReader reader = new JsonReader("{\"date\": \"invalid\"}");
reader.readStartDocument();
reader.readName("date");

OffsetDateTime result = dateCodec.decode(reader, DecoderContext.builder().build());

assertNull(result);
}

@Test
void encode_withValidOffsetDateTime_shouldWriteDateTime() {
OffsetDateTime dateTime = OffsetDateTime.of(2021, 12, 1, 0, 0, 0, 0, ZoneOffset.UTC);
StringWriter stringWriter = new StringWriter();
BsonWriter writer = new JsonWriter(stringWriter);

Assertions.assertDoesNotThrow(() -> dateCodec.encode(writer, dateTime, EncoderContext.builder().build()));
}

@Test
void getEncoderClass_shouldReturnOffsetDateTimeClass() {
assertEquals(OffsetDateTime.class, dateCodec.getEncoderClass());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import java.time.OffsetDateTime;

@Data
@SuppressWarnings("java:S1068")
public class UserNotificationToSend {

private String id;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@


@Data
@SuppressWarnings("java:S1068")
@FieldNameConstants(asEnum = true)
public class OnboardedProduct {

Expand Down

0 comments on commit 8b660c1

Please sign in to comment.