我有一个自定义的 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);
}
}
关于java - 如何使用 JUnit 和 Mockito 测试自定义 JsonSerializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31604236/