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 {

	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 {

	ObjectMapper objectMapper

	void "NoteKind is render as lowercase when serialized as JSON"() {
		MockPojo pojo = new MockPojo(kind: NoteKind.TRIX)
		objectMapper.writeValueAsString(pojo) == '{"kind":"trix"}'

	static class MockPojo {
		NoteKind kind

Tags: #micronaut #spock #jackson #test
May 2021, 07.