title: How can I write a JUnit-Test for custom Jackson Serializer?
body: <p>I wanted to test my serializer which parses my java object to a json object.  This is my Serializer class:       </p>
  
  <pre><code>public class CountryCodeSerializer extends JsonSerializer&lt;CountryCode&gt; {
  
      @Override
      public void serialize(CountryCode value, JsonGenerator generator, SerializerProvider provider)
              throws IOException, JsonProcessingException {
  
          if (value == null) {
              generator.writeString("{}");
          } else {
              generator.writeString(value.toString());
          }
      }
  
  }
  </code></pre>
  
  <p>My test looks like this:</p>
  
  <pre><code>    @Before
          public void setUp() throws Exception {
              stringJson = new StringWriter();
              generator = new JsonFactory().createGenerator(stringJson);
              provider = new ObjectMapper().getSerializerProvider();
              countryCode = CountryCode.parse("us");
          }
  
          @Test
          public void parsingNullReturnsNull() throws Exception {
              assertThat(countryCodeSerializer.serialize(countryCode, generator, provider)).isEqualTo("{'countrycode':'us'}); //this doesn't work, since serialize() is void
  
  //countryCodeSerializer.serialize(countryCode, generator, provider); //this throws an java.lang.NullPointerException
          }
  </code></pre>
  
  <p>So how can I test my serializer? I tried other answers to similar questions, but nothing worked for me. </p>
  
  <p>I use the serializer like this in my other clases:</p>
  
  <pre><code>@JsonSerialize(using = CountryCodeSerializer.class)
      private CountryCode countryCode;
  </code></pre>