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

My next events:
๐Ÿ—“ May 27 09:00 AWS Dublin - Micronaut and AWS Lambda
๐Ÿ—“ Jul 20 09:00 Workshop Security in the Micronaut Framework
๐Ÿ—“ Sep 20 09:00 JCON Online 2022 - Getting Started with the Micronaut Framework
๐Ÿ—“ Sep 23 09:00 JCON Online 2022 - Micronautยฎ Framework and Microstream Java-native persistence engine

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