如何使用JUnit和Mockito测试自定义JsonSerializer

时间:2015-07-24 07:04:41

标签: java junit 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并访问结果?

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

您可以这样做:

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);
    }

}