我有一个自定义的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);
}
}