Testing JSON serialization with Micronaut applications
The following enum uses Jackson's @JsonValue
annotation to render as lowercase string when serialized as JSON.
package example.micronaut;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.Locale;
public enum NoteKind {
TRIX;
@JsonValue
@Override
public String toString() {
return this.name().toLowerCase(Locale.ENGLISH);
}
}
We can test it with Spock by injecting the ObjectMapper
into your test:
package example.micronaut
import com.fasterxml.jackson.databind.ObjectMapper
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import spock.lang.Specification
import javax.inject.Inject
@MicronautTest(startApplication = false)
class NoteKindSpec extends Specification {
@Inject
ObjectMapper objectMapper
void "NoteKind is render as lowercase when serialized as JSON"() {
given:
MockPojo pojo = new MockPojo(kind: NoteKind.TRIX)
expect:
objectMapper.writeValueAsString(pojo) == '{"kind":"trix"}'
}
static class MockPojo {
NoteKind kind
}
}
Tags: #micronaut #spock #jackson #test