Refactor some tests to use ApplicationContextRunner

This commit is contained in:
Madhura Bhave 2018-01-02 16:56:50 -08:00
parent 3ab32df242
commit 716543828a
3 changed files with 282 additions and 349 deletions

View File

@ -19,12 +19,12 @@ package org.springframework.boot.autoconfigure.freemarker;
import java.io.StringWriter;
import java.util.Locale;
import org.junit.After;
import org.junit.Test;
import reactor.core.publisher.Mono;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebApplicationContext;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
@ -42,90 +42,83 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class FreeMarkerAutoConfigurationReactiveIntegrationTests {
private AnnotationConfigReactiveWebApplicationContext context = new AnnotationConfigReactiveWebApplicationContext();
@After
public void close() {
if (this.context != null) {
this.context.close();
}
}
private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(FreeMarkerAutoConfiguration.class));
@Test
public void defaultConfiguration() {
registerAndRefreshContext();
assertThat(this.context.getBean(FreeMarkerViewResolver.class)).isNotNull();
assertThat(this.context.getBean(FreeMarkerConfigurer.class)).isNotNull();
assertThat(this.context.getBean(FreeMarkerConfig.class)).isNotNull();
assertThat(this.context.getBean(freemarker.template.Configuration.class))
.isNotNull();
this.contextRunner.run(context -> {
assertThat(context.getBean(FreeMarkerViewResolver.class)).isNotNull();
assertThat(context.getBean(FreeMarkerConfigurer.class)).isNotNull();
assertThat(context.getBean(FreeMarkerConfig.class)).isNotNull();
assertThat(context.getBean(freemarker.template.Configuration.class))
.isNotNull();
});
}
@Test
public void defaultViewResolution() {
registerAndRefreshContext();
MockServerWebExchange exchange = render("home");
String result = exchange.getResponse().getBodyAsString().block();
assertThat(result).contains("home");
assertThat(exchange.getResponse().getHeaders().getContentType())
.isEqualTo(MediaType.TEXT_HTML);
this.contextRunner.run(context -> {
MockServerWebExchange exchange = render(context, "home");
String result = exchange.getResponse().getBodyAsString().block();
assertThat(result).contains("home");
assertThat(exchange.getResponse().getHeaders().getContentType())
.isEqualTo(MediaType.TEXT_HTML);
});
}
@Test
public void customPrefix() {
registerAndRefreshContext("spring.freemarker.prefix:prefix/");
MockServerWebExchange exchange = render("prefixed");
String result = exchange.getResponse().getBodyAsString().block();
assertThat(result).contains("prefixed");
this.contextRunner.withPropertyValues("spring.freemarker.prefix:prefix/").run(context -> {
MockServerWebExchange exchange = render(context, "prefixed");
String result = exchange.getResponse().getBodyAsString().block();
assertThat(result).contains("prefixed");
});
}
@Test
public void customSuffix() {
registerAndRefreshContext("spring.freemarker.suffix:.freemarker");
MockServerWebExchange exchange = render("suffixed");
String result = exchange.getResponse().getBodyAsString().block();
assertThat(result).contains("suffixed");
this.contextRunner.withPropertyValues("spring.freemarker.suffix:.freemarker").run(context -> {
MockServerWebExchange exchange = render(context, "suffixed");
String result = exchange.getResponse().getBodyAsString().block();
assertThat(result).contains("suffixed");
});
}
@Test
public void customTemplateLoaderPath() {
registerAndRefreshContext(
"spring.freemarker.templateLoaderPath:classpath:/custom-templates/");
MockServerWebExchange exchange = render("custom");
String result = exchange.getResponse().getBodyAsString().block();
assertThat(result).contains("custom");
this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:classpath:/custom-templates/").run(context -> {
MockServerWebExchange exchange = render(context, "custom");
String result = exchange.getResponse().getBodyAsString().block();
assertThat(result).contains("custom");
});
}
@SuppressWarnings("deprecation")
@Test
public void customFreeMarkerSettings() {
registerAndRefreshContext("spring.freemarker.settings.boolean_format:yup,nope");
assertThat(this.context.getBean(FreeMarkerConfigurer.class).getConfiguration()
.getSetting("boolean_format")).isEqualTo("yup,nope");
this.contextRunner.withPropertyValues("spring.freemarker.settings.boolean_format:yup,nope")
.run(context -> assertThat(context.getBean(FreeMarkerConfigurer.class).getConfiguration()
.getSetting("boolean_format")).isEqualTo("yup,nope"));
}
@Test
public void renderTemplate() throws Exception {
registerAndRefreshContext();
FreeMarkerConfigurer freemarker = this.context
.getBean(FreeMarkerConfigurer.class);
StringWriter writer = new StringWriter();
freemarker.getConfiguration().getTemplate("message.ftl").process(this, writer);
assertThat(writer.toString()).contains("Hello World");
}
private void registerAndRefreshContext(String... env) {
TestPropertyValues.of(env).applyTo(this.context);
this.context.register(FreeMarkerAutoConfiguration.class);
this.context.refresh();
public void renderTemplate() {
this.contextRunner.withPropertyValues().run(context -> {
FreeMarkerConfigurer freemarker = context
.getBean(FreeMarkerConfigurer.class);
StringWriter writer = new StringWriter();
freemarker.getConfiguration().getTemplate("message.ftl").process(this, writer);
assertThat(writer.toString()).contains("Hello World");
});
}
public String getGreeting() {
return "Hello World";
}
private MockServerWebExchange render(String viewName) {
FreeMarkerViewResolver resolver = this.context
private MockServerWebExchange render(ApplicationContext context, String viewName) {
FreeMarkerViewResolver resolver = context
.getBean(FreeMarkerViewResolver.class);
Mono<View> view = resolver.resolveViewName(viewName, Locale.UK);
MockServerWebExchange exchange = MockServerWebExchange

View File

@ -19,13 +19,12 @@ package org.springframework.boot.autoconfigure.freemarker;
import java.io.File;
import java.io.StringWriter;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
@ -41,24 +40,18 @@ public class FreeMarkerAutoConfigurationTests {
@Rule
public OutputCapture output = new OutputCapture();
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
private void registerAndRefreshContext(String... env) {
TestPropertyValues.of(env).applyTo(this.context);
this.context.register(FreeMarkerAutoConfiguration.class);
this.context.refresh();
}
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(FreeMarkerAutoConfiguration.class));
@Test
public void renderNonWebAppTemplate() throws Exception {
try (AnnotationConfigApplicationContext customContext = new AnnotationConfigApplicationContext(
FreeMarkerAutoConfiguration.class)) {
freemarker.template.Configuration freemarker = customContext
public void renderNonWebAppTemplate() {
this.contextRunner.run(context -> {
freemarker.template.Configuration freemarker = context
.getBean(freemarker.template.Configuration.class);
StringWriter writer = new StringWriter();
freemarker.getTemplate("message.ftl").process(this, writer);
assertThat(writer.toString()).contains("Hello World");
}
});
}
public String getGreeting() {
@ -67,30 +60,25 @@ public class FreeMarkerAutoConfigurationTests {
@Test
public void nonExistentTemplateLocation() {
registerAndRefreshContext("spring.freemarker.templateLoaderPath:"
+ "classpath:/does-not-exist/,classpath:/also-does-not-exist");
this.output.expect(containsString("Cannot find template location"));
this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:"
+ "classpath:/does-not-exist/,classpath:/also-does-not-exist")
.run(context -> this.output.expect(containsString("Cannot find template location")));
}
@Test
public void emptyTemplateLocation() {
new File("target/test-classes/templates/empty-directory").mkdir();
registerAndRefreshContext("spring.freemarker.templateLoaderPath:"
+ "classpath:/templates/empty-directory/");
this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:"
+ "classpath:/templates/empty-directory/").run(context -> {
});
}
@Test
public void nonExistentLocationAndEmptyLocation() {
new File("target/test-classes/templates/empty-directory").mkdir();
registerAndRefreshContext("spring.freemarker.templateLoaderPath:"
+ "classpath:/does-not-exist/,classpath:/templates/empty-directory/");
}
@After
public void close() {
if (this.context != null) {
this.context.close();
}
this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:"
+ "classpath:/does-not-exist/,classpath:/templates/empty-directory/").run(context -> {
});
}
}

View File

@ -47,15 +47,13 @@ import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDateTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.boot.jackson.JsonObjectSerializer;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@ -79,35 +77,24 @@ import static org.mockito.Mockito.mock;
*/
public class JacksonAutoConfigurationTests {
private AnnotationConfigApplicationContext context;
@Before
public void setUp() {
this.context = new AnnotationConfigApplicationContext();
}
@After
public void tearDown() {
if (this.context != null) {
this.context.close();
}
}
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class));
@Test
public void registersJodaModuleAutomatically() {
this.context.register(JacksonAutoConfiguration.class);
this.context.refresh();
ObjectMapper objectMapper = this.context.getBean(ObjectMapper.class);
assertThat(objectMapper.canSerialize(LocalDateTime.class)).isTrue();
this.contextRunner.run(context -> {
ObjectMapper objectMapper = context.getBean(ObjectMapper.class);
assertThat(objectMapper.canSerialize(LocalDateTime.class)).isTrue();
});
}
@Test
public void doubleModuleRegistration() throws Exception {
this.context.register(DoubleModulesConfig.class,
HttpMessageConvertersAutoConfiguration.class);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(mapper.writeValueAsString(new Foo())).isEqualTo("{\"foo\":\"bar\"}");
public void doubleModuleRegistration() {
this.contextRunner.withUserConfiguration(DoubleModulesConfig.class).withConfiguration(AutoConfigurations.of(
HttpMessageConvertersAutoConfiguration.class)).run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.writeValueAsString(new Foo())).isEqualTo("{\"foo\":\"bar\"}");
});
}
/*
@ -118,323 +105,288 @@ public class JacksonAutoConfigurationTests {
@Test
public void noCustomDateFormat() {
this.context.register(JacksonAutoConfiguration.class);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(mapper.getDateFormat()).isInstanceOf(StdDateFormat.class);
this.contextRunner.run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.getDateFormat()).isInstanceOf(StdDateFormat.class);
});
}
@Test
public void customDateFormat() {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues.of("spring.jackson.date-format:yyyyMMddHHmmss")
.applyTo(this.context);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
DateFormat dateFormat = mapper.getDateFormat();
assertThat(dateFormat).isInstanceOf(SimpleDateFormat.class);
assertThat(((SimpleDateFormat) dateFormat).toPattern())
.isEqualTo("yyyyMMddHHmmss");
this.contextRunner.withPropertyValues("spring.jackson.date-format:yyyyMMddHHmmss").run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
DateFormat dateFormat = mapper.getDateFormat();
assertThat(dateFormat).isInstanceOf(SimpleDateFormat.class);
assertThat(((SimpleDateFormat) dateFormat).toPattern())
.isEqualTo("yyyyMMddHHmmss");
});
}
@Test
public void customJodaDateTimeFormat() throws Exception {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues
.of("spring.jackson.date-format:yyyyMMddHHmmss",
"spring.jackson.joda-date-time-format:yyyy-MM-dd HH:mm:ss")
.applyTo(this.context);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC);
assertThat(mapper.writeValueAsString(dateTime))
.isEqualTo("\"1988-06-25 20:30:00\"");
Date date = dateTime.toDate();
assertThat(mapper.writeValueAsString(date)).isEqualTo("\"19880625203000\"");
this.contextRunner.withPropertyValues("spring.jackson.date-format:yyyyMMddHHmmss",
"spring.jackson.joda-date-time-format:yyyy-MM-dd HH:mm:ss").run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC);
assertThat(mapper.writeValueAsString(dateTime))
.isEqualTo("\"1988-06-25 20:30:00\"");
Date date = dateTime.toDate();
assertThat(mapper.writeValueAsString(date)).isEqualTo("\"19880625203000\"");
});
}
@Test
public void customDateFormatClass() {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues
.of("spring.jackson.date-format:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationTests.MyDateFormat")
.applyTo(this.context);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class);
this.contextRunner.withPropertyValues("spring.jackson.date-format:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationTests.MyDateFormat").run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class);
});
}
@Test
public void noCustomPropertyNamingStrategy() {
this.context.register(JacksonAutoConfiguration.class);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(mapper.getPropertyNamingStrategy()).isNull();
this.contextRunner.run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.getPropertyNamingStrategy()).isNull();
});
}
@Test
public void customPropertyNamingStrategyField() {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues.of("spring.jackson.property-naming-strategy:SNAKE_CASE")
.applyTo(this.context);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(mapper.getPropertyNamingStrategy())
.isInstanceOf(SnakeCaseStrategy.class);
this.contextRunner.withPropertyValues("spring.jackson.property-naming-strategy:SNAKE_CASE").run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.getPropertyNamingStrategy())
.isInstanceOf(SnakeCaseStrategy.class);
});
}
@Test
public void customPropertyNamingStrategyClass() {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues
.of("spring.jackson.property-naming-strategy:com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy")
.applyTo(this.context);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(mapper.getPropertyNamingStrategy())
.isInstanceOf(SnakeCaseStrategy.class);
this.contextRunner.withPropertyValues("spring.jackson.property-naming-strategy:com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy")
.run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.getPropertyNamingStrategy())
.isInstanceOf(SnakeCaseStrategy.class);
});
}
@Test
public void enableSerializationFeature() {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues.of("spring.jackson.serialization.indent_output:true")
.applyTo(this.context);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(SerializationFeature.INDENT_OUTPUT.enabledByDefault()).isFalse();
assertThat(mapper.getSerializationConfig()
.hasSerializationFeatures(SerializationFeature.INDENT_OUTPUT.getMask()))
.isTrue();
this.contextRunner.withPropertyValues("spring.jackson.serialization.indent_output:true")
.run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(SerializationFeature.INDENT_OUTPUT.enabledByDefault()).isFalse();
assertThat(mapper.getSerializationConfig()
.hasSerializationFeatures(SerializationFeature.INDENT_OUTPUT.getMask()))
.isTrue();
});
}
@Test
public void disableSerializationFeature() {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues
.of("spring.jackson.serialization.write_dates_as_timestamps:false")
.applyTo(this.context);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault())
.isTrue();
assertThat(mapper.getSerializationConfig().hasSerializationFeatures(
SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.getMask())).isFalse();
this.contextRunner.withPropertyValues("spring.jackson.serialization.write_dates_as_timestamps:false")
.run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault())
.isTrue();
assertThat(mapper.getSerializationConfig().hasSerializationFeatures(
SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.getMask())).isFalse();
});
}
@Test
public void enableDeserializationFeature() {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues
.of("spring.jackson.deserialization.use_big_decimal_for_floats:true")
.applyTo(this.context);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.enabledByDefault())
.isFalse();
assertThat(mapper.getDeserializationConfig().hasDeserializationFeatures(
DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.getMask())).isTrue();
this.contextRunner.withPropertyValues("spring.jackson.deserialization.use_big_decimal_for_floats:true")
.run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.enabledByDefault())
.isFalse();
assertThat(mapper.getDeserializationConfig().hasDeserializationFeatures(
DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.getMask())).isTrue();
});
}
@Test
public void disableDeserializationFeature() {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues
.of("spring.jackson.deserialization.fail-on-unknown-properties:false")
.applyTo(this.context);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault())
.isTrue();
assertThat(mapper.getDeserializationConfig().hasDeserializationFeatures(
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.getMask())).isFalse();
this.contextRunner.withPropertyValues("spring.jackson.deserialization.fail-on-unknown-properties:false")
.run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault())
.isTrue();
assertThat(mapper.getDeserializationConfig().hasDeserializationFeatures(
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.getMask())).isFalse();
});
}
@Test
public void enableMapperFeature() {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues.of("spring.jackson.mapper.require_setters_for_getters:true")
.applyTo(this.context);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault())
.isFalse();
assertThat(mapper.getSerializationConfig()
.hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask()))
.isTrue();
assertThat(mapper.getDeserializationConfig()
.hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask()))
.isTrue();
this.contextRunner.withPropertyValues("spring.jackson.mapper.require_setters_for_getters:true")
.run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault())
.isFalse();
assertThat(mapper.getSerializationConfig()
.hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask()))
.isTrue();
assertThat(mapper.getDeserializationConfig()
.hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask()))
.isTrue();
});
}
@Test
public void disableMapperFeature() {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues.of("spring.jackson.mapper.use_annotations:false")
.applyTo(this.context);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(MapperFeature.USE_ANNOTATIONS.enabledByDefault()).isTrue();
assertThat(mapper.getDeserializationConfig()
.hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())).isFalse();
assertThat(mapper.getSerializationConfig()
.hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())).isFalse();
this.contextRunner.withPropertyValues("spring.jackson.mapper.use_annotations:false")
.run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(MapperFeature.USE_ANNOTATIONS.enabledByDefault()).isTrue();
assertThat(mapper.getDeserializationConfig()
.hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())).isFalse();
assertThat(mapper.getSerializationConfig()
.hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())).isFalse();
});
}
@Test
public void enableParserFeature() {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues.of("spring.jackson.parser.allow_single_quotes:true")
.applyTo(this.context);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(JsonParser.Feature.ALLOW_SINGLE_QUOTES.enabledByDefault()).isFalse();
assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_SINGLE_QUOTES))
.isTrue();
this.contextRunner.withPropertyValues("spring.jackson.parser.allow_single_quotes:true")
.run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(JsonParser.Feature.ALLOW_SINGLE_QUOTES.enabledByDefault()).isFalse();
assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_SINGLE_QUOTES))
.isTrue();
});
}
@Test
public void disableParserFeature() {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues.of("spring.jackson.parser.auto_close_source:false")
.applyTo(this.context);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(JsonParser.Feature.AUTO_CLOSE_SOURCE.enabledByDefault()).isTrue();
assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE))
.isFalse();
this.contextRunner.withPropertyValues("spring.jackson.parser.auto_close_source:false")
.run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(JsonParser.Feature.AUTO_CLOSE_SOURCE.enabledByDefault()).isTrue();
assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE))
.isFalse();
});
}
@Test
public void enableGeneratorFeature() {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues.of("spring.jackson.generator.write_numbers_as_strings:true")
.applyTo(this.context);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS.enabledByDefault())
.isFalse();
assertThat(mapper.getFactory()
.isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)).isTrue();
this.contextRunner.withPropertyValues("spring.jackson.generator.write_numbers_as_strings:true")
.run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS.enabledByDefault())
.isFalse();
assertThat(mapper.getFactory()
.isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)).isTrue();
});
}
@Test
public void disableGeneratorFeature() {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues.of("spring.jackson.generator.auto_close_target:false")
.applyTo(this.context);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(JsonGenerator.Feature.AUTO_CLOSE_TARGET.enabledByDefault()).isTrue();
assertThat(mapper.getFactory().isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET))
.isFalse();
this.contextRunner.withPropertyValues("spring.jackson.generator.auto_close_target:false")
.run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(JsonGenerator.Feature.AUTO_CLOSE_TARGET.enabledByDefault()).isTrue();
assertThat(mapper.getFactory().isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET))
.isFalse();
});
}
@Test
public void defaultObjectMapperBuilder() {
this.context.register(JacksonAutoConfiguration.class);
this.context.refresh();
Jackson2ObjectMapperBuilder builder = this.context
.getBean(Jackson2ObjectMapperBuilder.class);
ObjectMapper mapper = builder.build();
assertThat(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()).isTrue();
assertThat(mapper.getDeserializationConfig()
.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse();
assertThat(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()).isTrue();
assertThat(mapper.getDeserializationConfig()
.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse();
assertThat(mapper.getSerializationConfig()
.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse();
assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault())
.isTrue();
assertThat(mapper.getDeserializationConfig()
.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse();
this.contextRunner.run(context -> {
Jackson2ObjectMapperBuilder builder = context
.getBean(Jackson2ObjectMapperBuilder.class);
ObjectMapper mapper = builder.build();
assertThat(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()).isTrue();
assertThat(mapper.getDeserializationConfig()
.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse();
assertThat(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()).isTrue();
assertThat(mapper.getDeserializationConfig()
.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse();
assertThat(mapper.getSerializationConfig()
.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse();
assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault())
.isTrue();
assertThat(mapper.getDeserializationConfig()
.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse();
});
}
@Test
public void moduleBeansAndWellKnownModulesAreRegisteredWithTheObjectMapperBuilder() {
this.context.register(ModuleConfig.class, JacksonAutoConfiguration.class);
this.context.refresh();
ObjectMapper objectMapper = this.context
.getBean(Jackson2ObjectMapperBuilder.class).build();
assertThat(this.context.getBean(CustomModule.class).getOwners())
.contains((ObjectCodec) objectMapper);
assertThat(objectMapper.canSerialize(LocalDateTime.class)).isTrue();
assertThat(objectMapper.canSerialize(Baz.class)).isTrue();
this.contextRunner.withUserConfiguration(ModuleConfig.class).run(context -> {
ObjectMapper objectMapper = context
.getBean(Jackson2ObjectMapperBuilder.class).build();
assertThat(context.getBean(CustomModule.class).getOwners())
.contains((ObjectCodec) objectMapper);
assertThat(objectMapper.canSerialize(LocalDateTime.class)).isTrue();
assertThat(objectMapper.canSerialize(Baz.class)).isTrue();
});
}
@Test
public void defaultSerializationInclusion() {
this.context.register(JacksonAutoConfiguration.class);
this.context.refresh();
ObjectMapper objectMapper = this.context
.getBean(Jackson2ObjectMapperBuilder.class).build();
assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion()
.getValueInclusion()).isEqualTo(JsonInclude.Include.USE_DEFAULTS);
this.contextRunner.run(context -> {
ObjectMapper objectMapper = context
.getBean(Jackson2ObjectMapperBuilder.class).build();
assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion()
.getValueInclusion()).isEqualTo(JsonInclude.Include.USE_DEFAULTS);
});
}
@Test
public void customSerializationInclusion() {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues.of("spring.jackson.default-property-inclusion:non_null")
.applyTo(this.context);
this.context.refresh();
ObjectMapper objectMapper = this.context
.getBean(Jackson2ObjectMapperBuilder.class).build();
assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion()
.getValueInclusion()).isEqualTo(JsonInclude.Include.NON_NULL);
this.contextRunner.withPropertyValues("spring.jackson.default-property-inclusion:non_null")
.run(context -> {
ObjectMapper objectMapper = context
.getBean(Jackson2ObjectMapperBuilder.class).build();
assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion()
.getValueInclusion()).isEqualTo(JsonInclude.Include.NON_NULL);
});
}
@Test
public void customTimeZoneFormattingADateTime() throws JsonProcessingException {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues.of("spring.jackson.time-zone:America/Los_Angeles")
.applyTo(this.context);
TestPropertyValues.of("spring.jackson.date-format:zzzz").applyTo(this.context);
TestPropertyValues.of("spring.jackson.locale:en").applyTo(this.context);
this.context.refresh();
ObjectMapper objectMapper = this.context
.getBean(Jackson2ObjectMapperBuilder.class).build();
DateTime dateTime = new DateTime(1436966242231L, DateTimeZone.UTC);
assertThat(objectMapper.writeValueAsString(dateTime))
.isEqualTo("\"Pacific Daylight Time\"");
public void customTimeZoneFormattingADateTime() {
this.contextRunner.withPropertyValues("spring.jackson.time-zone:America/Los_Angeles",
"spring.jackson.date-format:zzzz", "spring.jackson.locale:en").run(context -> {
ObjectMapper objectMapper = context
.getBean(Jackson2ObjectMapperBuilder.class).build();
DateTime dateTime = new DateTime(1436966242231L, DateTimeZone.UTC);
assertThat(objectMapper.writeValueAsString(dateTime))
.isEqualTo("\"Pacific Daylight Time\"");
});
}
@Test
public void customTimeZoneFormattingADate() throws JsonProcessingException {
this.context.register(JacksonAutoConfiguration.class);
TestPropertyValues.of("spring.jackson.time-zone:GMT+10").applyTo(this.context);
TestPropertyValues.of("spring.jackson.date-format:z").applyTo(this.context);
this.context.refresh();
ObjectMapper objectMapper = this.context
.getBean(Jackson2ObjectMapperBuilder.class).build();
Date date = new Date(1436966242231L);
assertThat(objectMapper.writeValueAsString(date)).isEqualTo("\"GMT+10:00\"");
this.contextRunner.withPropertyValues("spring.jackson.time-zone:GMT+10",
"spring.jackson.date-format:z").run(context -> {
ObjectMapper objectMapper = context
.getBean(Jackson2ObjectMapperBuilder.class).build();
Date date = new Date(1436966242231L);
assertThat(objectMapper.writeValueAsString(date)).isEqualTo("\"GMT+10:00\"");
});
}
@Test
public void customLocaleWithJodaTime() throws JsonProcessingException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(JacksonAutoConfiguration.class);
TestPropertyValues
.of("spring.jackson.locale:de_DE", "spring.jackson.date-format:zzzz",
"spring.jackson.serialization.write-dates-with-zone-id:true")
.applyTo(context);
context.refresh();
ObjectMapper objectMapper = context.getBean(ObjectMapper.class);
DateTime jodaTime = new DateTime(1478424650000L,
DateTimeZone.forID("Europe/Rome"));
assertThat(objectMapper.writeValueAsString(jodaTime))
.startsWith("\"Mitteleuropäische ");
this.contextRunner.withPropertyValues("spring.jackson.locale:de_DE", "spring.jackson.date-format:zzzz",
"spring.jackson.serialization.write-dates-with-zone-id:true").run(context -> {
ObjectMapper objectMapper = context.getBean(ObjectMapper.class);
DateTime jodaTime = new DateTime(1478424650000L,
DateTimeZone.forID("Europe/Rome"));
assertThat(objectMapper.writeValueAsString(jodaTime))
.startsWith("\"Mitteleuropäische ");
});
}
@Test
public void additionalJacksonBuilderCustomization() {
this.context.register(JacksonAutoConfiguration.class,
ObjectMapperBuilderCustomConfig.class);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class);
this.contextRunner.withUserConfiguration(ObjectMapperBuilderCustomConfig.class).run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class);
});
}
@Test
@ -450,27 +402,27 @@ public class JacksonAutoConfigurationTests {
}
@Test
public void writeDatesAsTimestampsDefault() throws Exception {
this.context.register(JacksonAutoConfiguration.class);
this.context.refresh();
ObjectMapper mapper = this.context.getBean(ObjectMapper.class);
DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC);
String expected = FormatConfig.DEFAULT_DATETIME_PRINTER.rawFormatter()
.withZone(DateTimeZone.UTC)
.print(dateTime);
assertThat(mapper.writeValueAsString(dateTime)).isEqualTo("\"" + expected + "\"");
public void writeDatesAsTimestampsDefault() {
this.contextRunner.run(context -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class);
DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC);
String expected = FormatConfig.DEFAULT_DATETIME_PRINTER.rawFormatter()
.withZone(DateTimeZone.UTC)
.print(dateTime);
assertThat(mapper.writeValueAsString(dateTime)).isEqualTo("\"" + expected + "\"");
});
}
private void assertParameterNamesModuleCreatorBinding(Mode expectedMode,
Class<?>... configClasses) {
this.context.register(configClasses);
this.context.refresh();
DeserializationConfig deserializationConfig = this.context
.getBean(ObjectMapper.class).getDeserializationConfig();
AnnotationIntrospector annotationIntrospector = deserializationConfig
.getAnnotationIntrospector().allIntrospectors().iterator().next();
assertThat(ReflectionTestUtils.getField(annotationIntrospector, "creatorBinding"))
.isEqualTo(expectedMode);
this.contextRunner.withUserConfiguration(configClasses).run(context -> {
DeserializationConfig deserializationConfig = context
.getBean(ObjectMapper.class).getDeserializationConfig();
AnnotationIntrospector annotationIntrospector = deserializationConfig
.getAnnotationIntrospector().allIntrospectors().iterator().next();
assertThat(ReflectionTestUtils.getField(annotationIntrospector, "creatorBinding"))
.isEqualTo(expectedMode);
});
}
public static class MyDateFormat extends SimpleDateFormat {