Skip to content

JsonJacksonApprovals doesn't work with Java 8 time types and the JSON output is not deterministic #743

@cgt

Description

@cgt

JsonJacksonApprovals creates the Jackson ObjectMapper by calling new ObjectMapper(). This ObjectMapper will not support Java 8 time types because support for that comes in a separate module (jackson-datatype-jsr310). Whenever I use approvals, I end up having to make my own copy of JsonJacksonApprovals where I change the asJson method to the following:

public static String asJson(Object o, Function1<ObjectMapper, ObjectMapper> objectMapperBuilder) {
    try {
        final var mapper = JsonMapper.builder()
            .findAndAddModules()
            .enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS)
            .enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)
            .build();
        ObjectMapper objectMapper = objectMapperBuilder.call(mapper);
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(o);
    } catch (JsonProcessingException e) {
        throw ObjectUtils.throwAsError(e);
    }
}

findAndAddModules automatically finds the Jackson Java 8 time module if available. Additionally, I enable two settings for ensuring that the output is deterministic. Without those settings, I've seen the fields change order in the document, which spuriously causes the approvals to fail.

Is there any particular reason why all these settings are not enabled by default? It would be great if I didn't have to copy and modify JsonJacksonApprovals every time I use it.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions