自定义日期序列化器的单元测试



我最近开始用Java编写测试,我对以下类的测试有一些问题。如何以这种形式为TestDateTimeSerializer类编写正确的测试。

public class TestDateTimeSerializer extends JsonSerializer<LocalDateTime> {
public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
@Override
public void serialize(LocalDateTime dt, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
if (dt == null) {
gen.writeNull();
} else {
gen.writeString(dt.format(FORMATTER));
}
}
}

这个类在这里使用

@Data
@JsonIgnoreProperties(ignoreUnknown = true) 
@JsonFormat(with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
public class TestRequest implements ITestResponse {
@JsonProperty("TestID")
private Long testID;
@JsonSerialize(using = TestDateTimeSerializer.class)
private LocalDateTime lastUpdateDate;
}

JsonGenerator作为模拟对象,然后验证其方法调用

@ExtendWith(MockitoExtension.class)
class TestDateTimeSerializerTest {
@Mock
JsonGenerator generator;       // JsonGenerator is mock
@Mock
SerializerProvider provider;
@Test
void test() throws IOException {
TestDateTimeSerializer serializer = new TestDateTimeSerializer();
LocalDateTime now = LocalDateTime.now();

// run your method
serializer.serialize(now, generator, provider);
// assert mocked generator's method call
verify(generator).writeString(ArgumentMatchers.anyString());
}
}

Mockito API doc: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#1

你可以找到更多的例子和用法。

请试试:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.junit.Before;
import org.junit.Test;
import java.time.LocalDateTime;
import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME;
import static org.junit.Assert.*;
public class TestDateTimeSerializerSerializerTest {
private ObjectMapper mapper;
protected TestDateTimeSerializer serializer;
@Before
public void setup() {
mapper = new ObjectMapper();
serializer = new TestDateTimeSerializer();
SimpleModule module = new SimpleModule();
module.addSerializer(LocalDateTime.class, serializer);
mapper.registerModule(module);
}
@Test
public void testSerializeNonNull() throws JsonProcessingException {
LocalDateTime ldt = LocalDateTime.parse("2016-10-06T10:40:21.124", ISO_LOCAL_DATE_TIME);
String serialized = mapper.writeValueAsString(ldt);
assertEquals("equal strings", ""2016-10-06T10:40:21.124Z"", serialized);
}
@Test
public void testSerializeNull() throws JsonProcessingException {
LocalDateTime ldt = null;
String serialized = mapper.writeValueAsString(ldt);
assertEquals("equal strings", "null", serialized);
}
}

相关内容

  • 没有找到相关文章

最新更新