如何使用 JUnit 和 Mockito 测试自定义 JsonSerializer
How to test custom JsonSerializer with JUnit and Mockito
我有一个自定义 JsonSerialzier 以特殊格式序列化日期:
public class CustomDateJsonSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException {
String outputDateValue;
//... do something with the Date and write the result into outputDateValue
gen.writeString(outputDateValue);
}
}
它工作正常,但我如何使用 JUnit 和 Mockito 测试我的代码?或者更确切地说,我如何模拟 JsonGenerator 并访问结果?
感谢您的帮助。
你可以这样做:
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
@RunWith(MockitoJUnitRunner.class)
public class CustomDateJsonSerializerTest {
@Mock
private JsonGenerator gen;
@Test
public void testOutputDateValue() {
CustomDateJsonSerializer serializer = new CustomDateJsonSerializer();
serializer.serialize(new Date(), gen, null /*or whatever it needs to be*/);
String expectedOutput = "whatever the correct output should be";
verify(gen, times(1)).writeString(expectedOutput);
}
}
我有一个自定义 JsonSerialzier 以特殊格式序列化日期:
public class CustomDateJsonSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException {
String outputDateValue;
//... do something with the Date and write the result into outputDateValue
gen.writeString(outputDateValue);
}
}
它工作正常,但我如何使用 JUnit 和 Mockito 测试我的代码?或者更确切地说,我如何模拟 JsonGenerator 并访问结果?
感谢您的帮助。
你可以这样做:
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
@RunWith(MockitoJUnitRunner.class)
public class CustomDateJsonSerializerTest {
@Mock
private JsonGenerator gen;
@Test
public void testOutputDateValue() {
CustomDateJsonSerializer serializer = new CustomDateJsonSerializer();
serializer.serialize(new Date(), gen, null /*or whatever it needs to be*/);
String expectedOutput = "whatever the correct output should be";
verify(gen, times(1)).writeString(expectedOutput);
}
}