From c6899d8d260f16dee183ac60bc34973eabbd84d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edd=C3=BA=20Mel=C3=A9ndez?= Date: Thu, 5 May 2022 22:49:25 -0500 Subject: [PATCH 1/4] SqlTemplate depends on flyway/liquibase execution See gh-537 --- mybatis-spring-boot-autoconfigure/pom.xml | 10 ++ ...pendsOnDatabaseInitializationDetector.java | 38 ++++++++ .../main/resources/META-INF/spring.factories | 4 + .../MybatisAutoConfigurationTest.java | 97 +++++++++++++++++++ .../db/changelog/db.changelog-city.yaml | 53 ++++++++++ .../db/changelog/db.changelog-master.yaml | 36 +++++++ .../db/changelog/db.changelog-override.json | 39 ++++++++ .../db/changelog/db.changelog-override.sql | 24 +++++ .../db/changelog/db.changelog-override.xml | 37 +++++++ .../test/resources/db/migration/V1__init.sql | 17 ++++ 10 files changed, 355 insertions(+) create mode 100644 mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/MybatisDependsOnDatabaseInitializationDetector.java create mode 100644 mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-city.yaml create mode 100644 mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-master.yaml create mode 100644 mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-override.json create mode 100644 mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-override.sql create mode 100644 mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-override.xml create mode 100644 mybatis-spring-boot-autoconfigure/src/test/resources/db/migration/V1__init.sql diff --git a/mybatis-spring-boot-autoconfigure/pom.xml b/mybatis-spring-boot-autoconfigure/pom.xml index 93f5f589d..88ed27ebd 100644 --- a/mybatis-spring-boot-autoconfigure/pom.xml +++ b/mybatis-spring-boot-autoconfigure/pom.xml @@ -109,6 +109,16 @@ spring-boot-starter-test test + + org.flywaydb + flyway-core + test + + + org.liquibase + liquibase-core + test + diff --git a/mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/MybatisDependsOnDatabaseInitializationDetector.java b/mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/MybatisDependsOnDatabaseInitializationDetector.java new file mode 100644 index 000000000..0f58fb52e --- /dev/null +++ b/mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/MybatisDependsOnDatabaseInitializationDetector.java @@ -0,0 +1,38 @@ +/* + * Copyright 2015-2022 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.mybatis.spring.boot.autoconfigure; + +import java.util.Collections; +import java.util.Set; + +import org.mybatis.spring.SqlSessionTemplate; +import org.springframework.boot.sql.init.dependency.AbstractBeansOfTypeDependsOnDatabaseInitializationDetector; +import org.springframework.boot.sql.init.dependency.DependsOnDatabaseInitializationDetector; + +/** + * {@link DependsOnDatabaseInitializationDetector} for Mybatis. + * + * @author Eddú Meléndez + */ +public class MybatisDependsOnDatabaseInitializationDetector + extends AbstractBeansOfTypeDependsOnDatabaseInitializationDetector { + + @Override + protected Set> getDependsOnDatabaseInitializationBeanTypes() { + return Collections.singleton(SqlSessionTemplate.class); + } + +} diff --git a/mybatis-spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories b/mybatis-spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories index c6c1b3735..512f5349f 100644 --- a/mybatis-spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories +++ b/mybatis-spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories @@ -2,3 +2,7 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration,\ org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration + +# Depends On Database Initialization Detectors +org.springframework.boot.sql.init.dependency.DependsOnDatabaseInitializationDetector=\ +org.mybatis.spring.boot.autoconfigure.MybatisDependsOnDatabaseInitializationDetector \ No newline at end of file diff --git a/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/MybatisAutoConfigurationTest.java b/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/MybatisAutoConfigurationTest.java index f12e835b3..dddbee4d4 100644 --- a/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/MybatisAutoConfigurationTest.java +++ b/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/MybatisAutoConfigurationTest.java @@ -50,6 +50,7 @@ import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.TypeHandlerRegistry; +import org.flywaydb.core.Flyway; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -76,17 +77,25 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.PropertiesFactoryBean; import org.springframework.beans.factory.config.RuntimeBeanReference; +import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; +import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration; +import org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer; import org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration; +import org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.support.SimpleThreadScope; +import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; +import liquibase.integration.spring.SpringLiquibase; + /** * Tests for {@link MybatisAutoConfiguration} * @@ -818,6 +827,58 @@ void testMybatisLanguageDriverAutoConfigurationWithSingleCandidateWhenDefaultLan assertThat(languageDriverRegistry.getDriver(ThymeleafLanguageDriver.class)).isNotNull(); } + @Test + void whenFlywayIsAutoConfiguredThenMybatisSqlSessionTemplateDependsOnFlywayBeans() { + ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class, MybatisAutoConfiguration.class)); + contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class).run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("sqlSessionTemplate"); + assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("flywayInitializer", "flyway"); + }); + } + + @Test + void whenCustomMigrationInitializerIsDefinedThenMybatisSqlSessionTemplateDependsOnIt() { + ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class, MybatisAutoConfiguration.class)); + contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayMigrationInitializer.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("sqlSessionTemplate"); + assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("flywayMigrationInitializer", "flyway"); + }); + } + + @Test + void whenCustomFlywayIsDefinedThenMybatisSqlSessionTemplateDependsOnIt() { + ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class, MybatisAutoConfiguration.class)); + contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlyway.class).run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("sqlSessionTemplate"); + assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("customFlyway"); + }); + } + + @Test + void whenLiquibaseIsAutoConfiguredThenMybatisSqlSessionTemplateDependsOnSpringLiquibaseBeans() { + ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class, MybatisAutoConfiguration.class)); + contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class).run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("sqlSessionTemplate"); + assertThat(beanDefinition.getDependsOn()).containsExactly("liquibase"); + }); + } + + @Test + void whenCustomSpringLiquibaseIsDefinedThenMybatisSqlSessionTemplateDependsOnSpringLiquibaseBeans() { + ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class, MybatisAutoConfiguration.class)); + contextRunner.withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("sqlSessionTemplate"); + assertThat(beanDefinition.getDependsOn()).containsExactly("springLiquibase"); + }); + } + @Configuration static class MultipleDataSourceConfiguration { @Bean @@ -1123,4 +1184,40 @@ public UUID getNullableResult(CallableStatement cs, int columnIndex) { } + @Configuration(proxyBeanMethods = false) + static class CustomFlywayMigrationInitializer { + + @Bean + FlywayMigrationInitializer flywayMigrationInitializer(Flyway flyway) { + FlywayMigrationInitializer initializer = new FlywayMigrationInitializer(flyway); + initializer.setOrder(Ordered.HIGHEST_PRECEDENCE); + return initializer; + } + + } + + @Configuration(proxyBeanMethods = false) + static class CustomFlyway { + + @Bean + Flyway customFlyway() { + return Flyway.configure().load(); + } + + } + + @Configuration(proxyBeanMethods = false) + static class LiquibaseUserConfiguration { + + @Bean + SpringLiquibase springLiquibase(DataSource dataSource) { + SpringLiquibase liquibase = new SpringLiquibase(); + liquibase.setChangeLog("classpath:/db/changelog/db.changelog-master.yaml"); + liquibase.setShouldRun(true); + liquibase.setDataSource(dataSource); + return liquibase; + } + + } + } diff --git a/mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-city.yaml b/mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-city.yaml new file mode 100644 index 000000000..a7536a141 --- /dev/null +++ b/mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-city.yaml @@ -0,0 +1,53 @@ +# +# Copyright 2015-2022 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +databaseChangeLog: + - changeSet: + id: 1 + author: dsyer + changes: + - createSequence: + sequenceName: hibernate_sequence + - createTable: + tableName: city + columns: + - column: + name: id + type: bigint + autoIncrement: true + constraints: + primaryKey: true + nullable: false + - column: + name: name + type: varchar(50) + constraints: + nullable: false + - column: + name: state + type: varchar(50) + constraints: + nullable: false + - column: + name: country + type: varchar(50) + constraints: + nullable: false + - column: + name: map + type: varchar(50) + constraints: + nullable: true diff --git a/mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-master.yaml b/mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-master.yaml new file mode 100644 index 000000000..719384a6f --- /dev/null +++ b/mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-master.yaml @@ -0,0 +1,36 @@ +# +# Copyright 2015-2022 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +databaseChangeLog: + - changeSet: + id: 1 + author: marceloverdijk + changes: + - createTable: + tableName: customer + columns: + - column: + name: id + type: int + autoIncrement: true + constraints: + primaryKey: true + nullable: false + - column: + name: name + type: varchar(50) + constraints: + nullable: false diff --git a/mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-override.json b/mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-override.json new file mode 100644 index 000000000..acaa0e211 --- /dev/null +++ b/mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-override.json @@ -0,0 +1,39 @@ +{ + "databaseChangeLog": [ + { + "changeSet": { + "author": "awilkinson", + "id": "1", + "changes": [ + { + "createTable": { + "tableName": "customer", + "columns": [ + { + "column": { + "name": "id", + "type": "int", + "autoIncrement": true, + "constraints": { + "nullable": false, + "primaryKey": true + } + } + }, + { + "column": { + "name": "name", + "type": "varchar(50)", + "constraints": { + "nullable": false + } + } + } + ] + } + } + ] + } + } + ] +} diff --git a/mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-override.sql b/mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-override.sql new file mode 100644 index 000000000..70d1a4426 --- /dev/null +++ b/mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-override.sql @@ -0,0 +1,24 @@ +-- +-- Copyright 2015-2022 the original author or authors. +-- +-- Licensed under the Apache License, Version 2.0 (the "License"); +-- you may not use this file except in compliance with the License. +-- You may obtain a copy of the License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +-- See the License for the specific language governing permissions and +-- limitations under the License. +-- + +--liquibase formatted sql + +--changeset author:awilkinson + +CREATE TABLE customer ( + id int AUTO_INCREMENT NOT NULL PRIMARY KEY, + name varchar(50) NOT NULL +); \ No newline at end of file diff --git a/mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-override.xml b/mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-override.xml new file mode 100644 index 000000000..28a428d3c --- /dev/null +++ b/mybatis-spring-boot-autoconfigure/src/test/resources/db/changelog/db.changelog-override.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + diff --git a/mybatis-spring-boot-autoconfigure/src/test/resources/db/migration/V1__init.sql b/mybatis-spring-boot-autoconfigure/src/test/resources/db/migration/V1__init.sql new file mode 100644 index 000000000..c2e0bfa11 --- /dev/null +++ b/mybatis-spring-boot-autoconfigure/src/test/resources/db/migration/V1__init.sql @@ -0,0 +1,17 @@ +-- +-- Copyright 2015-2022 the original author or authors. +-- +-- Licensed under the Apache License, Version 2.0 (the "License"); +-- you may not use this file except in compliance with the License. +-- You may obtain a copy of the License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +-- See the License for the specific language governing permissions and +-- limitations under the License. +-- + +DROP TABLE IF EXISTS TEST; From 766195bcbc06eefe3e6945db28bd8c84f9f71233 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edd=C3=BA=20Mel=C3=A9ndez?= Date: Fri, 6 May 2022 09:05:19 -0500 Subject: [PATCH 2/4] Move to contextRunner and fix tests --- ...pendsOnDatabaseInitializationDetector.java | 2 +- .../MybatisAutoConfigurationTest.java | 1063 ++++++++--------- ...isLanguageDriverAutoConfigurationTest.java | 477 ++++---- .../TestAutoConfigurationPackage.java | 36 + ...TestAutoConfigurationPackageRegistrar.java | 39 + 5 files changed, 832 insertions(+), 785 deletions(-) create mode 100644 mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/TestAutoConfigurationPackage.java create mode 100644 mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java diff --git a/mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/MybatisDependsOnDatabaseInitializationDetector.java b/mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/MybatisDependsOnDatabaseInitializationDetector.java index 0f58fb52e..fb89bca78 100644 --- a/mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/MybatisDependsOnDatabaseInitializationDetector.java +++ b/mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/MybatisDependsOnDatabaseInitializationDetector.java @@ -27,7 +27,7 @@ * * @author Eddú Meléndez */ -public class MybatisDependsOnDatabaseInitializationDetector +class MybatisDependsOnDatabaseInitializationDetector extends AbstractBeansOfTypeDependsOnDatabaseInitializationDetector { @Override diff --git a/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/MybatisAutoConfigurationTest.java b/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/MybatisAutoConfigurationTest.java index dddbee4d4..a2823f146 100644 --- a/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/MybatisAutoConfigurationTest.java +++ b/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/MybatisAutoConfigurationTest.java @@ -16,7 +16,6 @@ package org.mybatis.spring.boot.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; import com.example.mapper.DateTimeMapper; @@ -51,8 +50,6 @@ import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.TypeHandlerRegistry; import org.flywaydb.core.Flyway; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.mybatis.scripting.freemarker.FreeMarkerLanguageDriver; @@ -78,15 +75,12 @@ import org.springframework.beans.factory.config.PropertiesFactoryBean; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration; import org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer; import org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration; import org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; @@ -105,726 +99,726 @@ */ class MybatisAutoConfigurationTest { - private AnnotationConfigApplicationContext context; - - @BeforeEach - void init() { - this.context = new AnnotationConfigApplicationContext(); - } - - @AfterEach - void closeContext() { - if (this.context != null) { - this.context.close(); - } - } + private ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(MybatisAutoConfiguration.class)); @Test void testNoDataSource() { - this.context.register(MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).isEmpty(); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).isEmpty(); - assertThat(this.context.getBeanNamesForType(MybatisProperties.class)).isEmpty(); + this.contextRunner.withUserConfiguration(PropertyPlaceholderAutoConfiguration.class).run(context -> { + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).isEmpty(); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).isEmpty(); + assertThat(context.getBeanNamesForType(MybatisProperties.class)).isEmpty(); + }); } @Test void testMultipleDataSource() { - this.context.register(MultipleDataSourceConfiguration.class, MybatisAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).isEmpty(); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).isEmpty(); - assertThat(this.context.getBeanNamesForType(MybatisProperties.class)).isEmpty(); + this.contextRunner + .withUserConfiguration(MultipleDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class) + .run(context -> { + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).isEmpty(); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).isEmpty(); + assertThat(context.getBeanNamesForType(MybatisProperties.class)).isEmpty(); + }); } @Test void testSingleCandidateDataSource() { - this.context.register(SingleCandidateDataSourceConfiguration.class, MybatisAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(MybatisProperties.class)).hasSize(1); + this.contextRunner + .withUserConfiguration(SingleCandidateDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class) + .run(context -> { + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBeanNamesForType(MybatisProperties.class)).hasSize(1); + }); } @Test void testDefaultConfiguration() { - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisScanMapperConfiguration.class, - MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - SqlSessionFactory sqlSessionFactory = this.context.getBean(SqlSessionFactory.class); - assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(DateTimeMapper.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.SIMPLE); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()).isFalse(); - Map languageDriverBeans = this.context.getBeansOfType(LanguageDriver.class); - assertThat(languageDriverBeans).hasSize(3).containsKeys("freeMarkerLanguageDriver", "velocityLanguageDriver", - "thymeleafLanguageDriver"); - assertThat(languageDriverBeans.get("freeMarkerLanguageDriver")).isInstanceOf(FreeMarkerLanguageDriver.class); - assertThat(languageDriverBeans.get("velocityLanguageDriver")).isInstanceOf(VelocityLanguageDriver.class); - assertThat(languageDriverBeans.get("thymeleafLanguageDriver")).isInstanceOf(ThymeleafLanguageDriver.class); - LanguageDriverRegistry languageDriverRegistry = sqlSessionFactory.getConfiguration().getLanguageRegistry(); - assertThat(languageDriverRegistry.getDefaultDriverClass()).isEqualTo(XMLLanguageDriver.class); - assertThat(languageDriverRegistry.getDefaultDriver()).isInstanceOf(XMLLanguageDriver.class); - assertThat(languageDriverRegistry.getDriver(XMLLanguageDriver.class)).isNotNull(); - assertThat(languageDriverRegistry.getDriver(RawLanguageDriver.class)).isNotNull(); - assertThat(languageDriverRegistry.getDriver(FreeMarkerLanguageDriver.class)).isNotNull(); - assertThat(languageDriverRegistry.getDriver(VelocityLanguageDriver.class)).isNotNull(); - assertThat(languageDriverRegistry.getDriver(ThymeleafLanguageDriver.class)).isNotNull(); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisLanguageDriverAutoConfiguration.class, + MybatisScanMapperConfiguration.class, PropertyPlaceholderAutoConfiguration.class) + .run(context -> { + SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class); + assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBeanNamesForType(DateTimeMapper.class)).hasSize(1); + assertThat(context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.SIMPLE); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()) + .isFalse(); + Map languageDriverBeans = context.getBeansOfType(LanguageDriver.class); + assertThat(languageDriverBeans).hasSize(3).containsKeys("freeMarkerLanguageDriver", "velocityLanguageDriver", + "thymeleafLanguageDriver"); + assertThat(languageDriverBeans.get("freeMarkerLanguageDriver")).isInstanceOf(FreeMarkerLanguageDriver.class); + assertThat(languageDriverBeans.get("velocityLanguageDriver")).isInstanceOf(VelocityLanguageDriver.class); + assertThat(languageDriverBeans.get("thymeleafLanguageDriver")).isInstanceOf(ThymeleafLanguageDriver.class); + LanguageDriverRegistry languageDriverRegistry = sqlSessionFactory.getConfiguration().getLanguageRegistry(); + assertThat(languageDriverRegistry.getDefaultDriverClass()).isEqualTo(XMLLanguageDriver.class); + assertThat(languageDriverRegistry.getDefaultDriver()).isInstanceOf(XMLLanguageDriver.class); + assertThat(languageDriverRegistry.getDriver(XMLLanguageDriver.class)).isNotNull(); + assertThat(languageDriverRegistry.getDriver(RawLanguageDriver.class)).isNotNull(); + assertThat(languageDriverRegistry.getDriver(FreeMarkerLanguageDriver.class)).isNotNull(); + assertThat(languageDriverRegistry.getDriver(VelocityLanguageDriver.class)).isNotNull(); + assertThat(languageDriverRegistry.getDriver(ThymeleafLanguageDriver.class)).isNotNull(); + }); } @Test void testScanWithLazy() { - TestPropertyValues.of("mybatis.lazy-initialization:true").applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisScanMapperConfiguration.class, - MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - SqlSessionFactory sqlSessionFactory = this.context.getBean(SqlSessionFactory.class); - assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(0); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(DateTimeMapper.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.SIMPLE); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()).isFalse(); - this.context.getBean(DateTimeMapper.class); - assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisScanMapperConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .withPropertyValues("mybatis.lazy-initialization:true").run(context -> { + SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class); + assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(0); + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBeanNamesForType(DateTimeMapper.class)).hasSize(1); + assertThat(context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.SIMPLE); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()) + .isFalse(); + context.getBean(DateTimeMapper.class); + assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); + }); } @Test void testAutoScanWithDefault() { - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, - MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - SqlSessionFactory sqlSessionFactory = this.context.getBean(SqlSessionFactory.class); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(CityMapper.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.SIMPLE); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()).isFalse(); - this.context.getBean(CityMapper.class); - assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); - assertThat(((RuntimeBeanReference) this.context.getBeanDefinition("cityMapper").getPropertyValues() - .getPropertyValue("sqlSessionTemplate").getValue()).getBeanName()).isEqualTo("sqlSessionTemplate"); - assertThat( - this.context.getBeanDefinition(this.context.getBeanNamesForType(MapperScannerConfigurer.class)[0]).getRole()) - .isEqualTo(BeanDefinition.ROLE_INFRASTRUCTURE); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, CityMapperRepositoryConfiguration.class) + .run(context -> { + SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class); + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBeanNamesForType(CityMapper.class)).hasSize(1); + assertThat(context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.SIMPLE); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()) + .isFalse(); + context.getBean(CityMapper.class); + assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); + assertThat(((RuntimeBeanReference) context.getBeanFactory().getBeanDefinition("cityMapper") + .getPropertyValues().getPropertyValue("sqlSessionTemplate").getValue()).getBeanName()) + .isEqualTo("sqlSessionTemplate"); + assertThat(context.getBeanFactory() + .getBeanDefinition(context.getBeanNamesForType(MapperScannerConfigurer.class)[0]).getRole()) + .isEqualTo(BeanDefinition.ROLE_INFRASTRUCTURE); + }); } @Test void testAutoScanWithInjectSqlSessionOnMapperScanIsFalse() { - TestPropertyValues.of("mybatis.inject-sql-session-on-mapper-scan:false").applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, - MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - SqlSessionFactory sqlSessionFactory = this.context.getBean(SqlSessionFactory.class); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(CityMapper.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.SIMPLE); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()).isFalse(); - this.context.getBean(CityMapper.class); - assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); - assertThat(this.context.getBeanDefinition("cityMapper").getPropertyValues().getPropertyValue("sqlSessionTemplate")) - .isNull(); - assertThat(this.context.getBeanDefinition("cityMapper").getPropertyValues().getPropertyValue("sqlSessionFactory")) - .isNull(); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, CityMapperRepositoryConfiguration.class) + .withPropertyValues("mybatis.inject-sql-session-on-mapper-scan:false").run(context -> { + SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class); + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBeanNamesForType(CityMapper.class)).hasSize(1); + assertThat(context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.SIMPLE); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()) + .isFalse(); + context.getBean(CityMapper.class); + assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); + assertThat(context.getBeanFactory().getBeanDefinition("cityMapper").getPropertyValues() + .getPropertyValue("sqlSessionTemplate")).isNull(); + assertThat(context.getBeanFactory().getBeanDefinition("cityMapper").getPropertyValues() + .getPropertyValue("sqlSessionFactory")).isNull(); + }); } @Test void testAutoScanWithLazy() { - TestPropertyValues.of("mybatis.lazy-initialization:true").applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, - MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - SqlSessionFactory sqlSessionFactory = this.context.getBean(SqlSessionFactory.class); - assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(0); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(CityMapper.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.SIMPLE); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()).isFalse(); - this.context.getBean(CityMapper.class); - assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, CityMapperRepositoryConfiguration.class) + .withPropertyValues("mybatis.lazy-initialization:true").run(context -> { + SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class); + assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(0); + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBeanNamesForType(CityMapper.class)).hasSize(1); + assertThat(context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.SIMPLE); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()) + .isFalse(); + context.getBean(CityMapper.class); + assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); + }); } @Test void testAutoScanWithDefaultScope() { - TestPropertyValues.of("mybatis.mapper-default-scope:thread").applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, - MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - { - this.context.getBean(CityMapper.class); - BeanDefinition bd = this.context.getBeanDefinition("cityMapper"); - assertThat(bd.getBeanClassName()).isEqualTo(ScopedProxyFactoryBean.class.getName()); - BeanDefinition spbd = this.context.getBeanDefinition("scopedTarget.cityMapper"); - assertThat(spbd.getBeanClassName()).isEqualTo(MapperFactoryBean.class.getName()); - assertThat(spbd.getScope()).isEqualTo("thread"); - } + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, CityMapperRepositoryConfiguration.class) + .withPropertyValues("mybatis.mapper-default-scope:thread").run(context -> { + context.getBean(CityMapper.class); + BeanDefinition bd = context.getBeanFactory().getBeanDefinition("cityMapper"); + assertThat(bd.getBeanClassName()).isEqualTo(ScopedProxyFactoryBean.class.getName()); + BeanDefinition spbd = context.getBeanFactory().getBeanDefinition("scopedTarget.cityMapper"); + assertThat(spbd.getBeanClassName()).isEqualTo(MapperFactoryBean.class.getName()); + assertThat(spbd.getScope()).isEqualTo("thread"); + }); } @Test void testAutoScanWithoutDefaultScope() { - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, - MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - { - this.context.getBean(CityMapper.class); - BeanDefinition df = this.context.getBeanDefinition("cityMapper"); - assertThat(df.getBeanClassName()).isEqualTo(MapperFactoryBean.class.getName()); - assertThat(df.getScope()).isEqualTo("singleton"); - } + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, CityMapperRepositoryConfiguration.class) + .run(context -> { + context.getBean(CityMapper.class); + BeanDefinition df = context.getBeanFactory().getBeanDefinition("cityMapper"); + assertThat(df.getBeanClassName()).isEqualTo(MapperFactoryBean.class.getName()); + assertThat(df.getScope()).isEqualTo("singleton"); + }); } @Test void testWithConfigLocation() { - TestPropertyValues.of("mybatis.config-location:mybatis-config.xml").applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class, - MybatisMapperConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(CityMapperImpl.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.BATCH); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()).isTrue(); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisMapperConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .withPropertyValues("mybatis.config-location:mybatis-config.xml").run(context -> { + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(CityMapperImpl.class)).hasSize(1); + assertThat(context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.BATCH); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()).isTrue(); + }); } @Test void testWithCheckConfigLocationFileExists() { - TestPropertyValues.of("mybatis.config-location:mybatis-config.xml", "mybatis.check-config-location=true") - .applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class) + .withPropertyValues("mybatis.config-location:mybatis-config.xml", "mybatis.check-config-location=true") + .run(context -> assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1)); } @Test void testWithCheckConfigLocationFileNotSpecify() { - TestPropertyValues.of("mybatis.check-config-location=true").applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) + .withPropertyValues("mybatis.check-config-location=true") + .run(context -> assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1)); } @Test void testWithCheckConfigLocationFileDoesNotExists() { - - TestPropertyValues.of("mybatis.config-location:foo.xml", "mybatis.check-config-location=true") - .applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class); - - try { - this.context.refresh(); - fail("Should be occurred a BeanCreationException."); - } catch (BeanCreationException e) { - assertThat(e.getMessage()).isEqualTo( - "Error creating bean with name 'mybatisAutoConfiguration': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot find config location: class path resource [foo.xml] (please add config file or check your Mybatis configuration)"); - } + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) + .withPropertyValues("mybatis.config-location:foo.xml", "mybatis.check-config-location=true") + .run(context -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class).hasMessageContaining( + "Error creating bean with name 'mybatisAutoConfiguration': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot find config location: class path resource [foo.xml] (please add config file or check your Mybatis configuration)")); } @Test void testWithTypeHandlersPackage() { - TestPropertyValues.of("mybatis.type-handlers-package:org.mybatis.spring.boot.autoconfigure.handler") - .applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - - TypeHandlerRegistry typeHandlerRegistry = this.context.getBean(SqlSessionFactory.class).getConfiguration() - .getTypeHandlerRegistry(); - assertThat(typeHandlerRegistry.hasTypeHandler(BigInteger.class)).isTrue(); - assertThat(typeHandlerRegistry.hasTypeHandler(AtomicInteger.class)).isTrue(); - assertThat(typeHandlerRegistry.hasTypeHandler(AtomicLong.class)).isTrue(); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class) + .withPropertyValues("mybatis.type-handlers-package:org.mybatis.spring.boot.autoconfigure.handler") + .run(context -> { + TypeHandlerRegistry typeHandlerRegistry = context.getBean(SqlSessionFactory.class).getConfiguration() + .getTypeHandlerRegistry(); + assertThat(typeHandlerRegistry.hasTypeHandler(BigInteger.class)).isTrue(); + assertThat(typeHandlerRegistry.hasTypeHandler(AtomicInteger.class)).isTrue(); + assertThat(typeHandlerRegistry.hasTypeHandler(AtomicLong.class)).isTrue(); + }); } @Test void testWithMapperLocation() { - TestPropertyValues - .of("mybatis.type-aliases-package:org.mybatis.spring.boot.autoconfigure.domain", + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class) + .withPropertyValues("mybatis.type-aliases-package:org.mybatis.spring.boot.autoconfigure.domain", "mybatis.mapper-locations:classpath:org/mybatis/spring/boot/autoconfigure/repository/CityMapper.xml") - .applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().getMappedStatementNames()).hasSize(2); + .run( + context -> assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().getMappedStatementNames()) + .hasSize(2)); } @Test void testWithExecutorType() { - TestPropertyValues.of("mybatis.config-location:mybatis-config.xml", "mybatis.executor-type:REUSE") - .applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class, - MybatisMapperConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.REUSE); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisMapperConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .withPropertyValues("mybatis.config-location:mybatis-config.xml", "mybatis.executor-type:REUSE") + .run(context -> assertThat(context.getBean(SqlSessionTemplate.class).getExecutorType()) + .isEqualTo(ExecutorType.REUSE)); } @Test void testDefaultBootConfiguration() { - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, - MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - SqlSessionFactory sqlSessionFactory = this.context.getBean(SqlSessionFactory.class); - assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(CityMapper.class)).hasSize(1); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, CityMapperRepositoryConfiguration.class) + .run(context -> { + SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class); + assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBeanNamesForType(CityMapper.class)).hasSize(1); + }); } @Test void testWithInterceptorsOrder1() { - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisInterceptorConfiguration.class, - MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().getInterceptors()).hasSize(2); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().getInterceptors().get(0)) - .isInstanceOf(MyInterceptor2.class); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().getInterceptors().get(1)) - .isInstanceOf(MyInterceptor.class); - - this.context.close(); + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, + MybatisInterceptorConfiguration.class, PropertyPlaceholderAutoConfiguration.class).run(context -> { + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().getInterceptors()).hasSize(2); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().getInterceptors().get(0)) + .isInstanceOf(MyInterceptor2.class); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().getInterceptors().get(1)) + .isInstanceOf(MyInterceptor.class); + }); } @Test void testWithInterceptorsOrder2() { - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisInterceptorConfiguration2.class, - MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().getInterceptors()).hasSize(2); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().getInterceptors().get(0)) - .isInstanceOf(MyInterceptor.class); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().getInterceptors().get(1)) - .isInstanceOf(MyInterceptor2.class); - - this.context.close(); + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, + MybatisInterceptorConfiguration2.class, PropertyPlaceholderAutoConfiguration.class).run(context -> { + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().getInterceptors()).hasSize(2); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().getInterceptors().get(0)) + .isInstanceOf(MyInterceptor.class); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().getInterceptors().get(1)) + .isInstanceOf(MyInterceptor2.class); + }); } @Test void testWithTypeHandlers() { - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisTypeHandlerConfiguration.class, - MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().getTypeHandlerRegistry() - .getTypeHandler(UUID.class)).isInstanceOf(MyTypeHandler.class); - this.context.close(); + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, + MybatisTypeHandlerConfiguration.class, PropertyPlaceholderAutoConfiguration.class).run(context -> { + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().getTypeHandlerRegistry() + .getTypeHandler(UUID.class)).isInstanceOf(MyTypeHandler.class); + }); } @Test void testWithDatabaseIdProvider() { - this.context.register(EmbeddedDataSourceConfiguration.class, DatabaseProvidersConfiguration.class, - MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().getDatabaseId()).isEqualTo("h2"); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, DatabaseProvidersConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .run(context -> assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().getDatabaseId()) + .isEqualTo("h2")); } @Test void testMixedWithConfigurationFileAndInterceptor() { - TestPropertyValues.of("mybatis.config-location:mybatis-config-settings-only.xml").applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisInterceptorConfiguration.class); - this.context.refresh(); - - org.apache.ibatis.session.Configuration configuration = this.context.getBean(SqlSessionFactory.class) - .getConfiguration(); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(CityMapper.class)).hasSize(1); - assertThat(configuration.getDefaultFetchSize()).isEqualTo(1000); - assertThat(configuration.getInterceptors()).hasSize(2); - assertThat(configuration.getInterceptors().get(0)).isInstanceOf(MyInterceptor2.class); - assertThat(configuration.getInterceptors().get(1)).isInstanceOf(MyInterceptor.class); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisInterceptorConfiguration.class, + CityMapperRepositoryConfiguration.class) + .withPropertyValues("mybatis.config-location:mybatis-config-settings-only.xml").run(context -> { + org.apache.ibatis.session.Configuration configuration = context.getBean(SqlSessionFactory.class) + .getConfiguration(); + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBeanNamesForType(CityMapper.class)).hasSize(1); + assertThat(configuration.getDefaultFetchSize()).isEqualTo(1000); + assertThat(configuration.getInterceptors()).hasSize(2); + assertThat(configuration.getInterceptors().get(0)).isInstanceOf(MyInterceptor2.class); + assertThat(configuration.getInterceptors().get(1)).isInstanceOf(MyInterceptor.class); + }); } @Test void testMixedWithConfigurationFileAndDatabaseIdProvider() { - TestPropertyValues.of("mybatis.config-location:mybatis-config-settings-only.xml").applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, - DatabaseProvidersConfiguration.class); - this.context.refresh(); - - org.apache.ibatis.session.Configuration configuration = this.context.getBean(SqlSessionFactory.class) - .getConfiguration(); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(CityMapper.class)).hasSize(1); - assertThat(configuration.getDefaultFetchSize()).isEqualTo(1000); - assertThat(configuration.getDatabaseId()).isEqualTo("h2"); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, + DatabaseProvidersConfiguration.class, CityMapperRepositoryConfiguration.class) + .withPropertyValues("mybatis.config-location:mybatis-config-settings-only.xml").run(context -> { + org.apache.ibatis.session.Configuration configuration = context.getBean(SqlSessionFactory.class) + .getConfiguration(); + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBeanNamesForType(CityMapper.class)).hasSize(1); + assertThat(configuration.getDefaultFetchSize()).isEqualTo(1000); + assertThat(configuration.getDatabaseId()).isEqualTo("h2"); + }); } @Test void testMixedWithConfigurationFileAndTypeHandlersPackage() { - TestPropertyValues.of("mybatis.config-location:mybatis-config-settings-only.xml", - "mybatis.type-handlers-package:org.mybatis.spring.boot.autoconfigure.handler.").applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class); - this.context.refresh(); - - org.apache.ibatis.session.Configuration configuration = this.context.getBean(SqlSessionFactory.class) - .getConfiguration(); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(CityMapper.class)).hasSize(1); - assertThat(configuration.getDefaultFetchSize()).isEqualTo(1000); - assertThat(configuration.getTypeHandlerRegistry().getTypeHandler(BigInteger.class)) - .isInstanceOf(DummyTypeHandler.class); - assertThat(configuration.getTypeHandlerRegistry().getTypeHandler(AtomicInteger.class)) - .isInstanceOf(AtomicNumberTypeHandler.class); - assertThat(configuration.getTypeHandlerRegistry().getTypeHandler(AtomicLong.class)) - .isInstanceOf(AtomicNumberTypeHandler.class); - assertThat(configuration.getTypeHandlerRegistry().getTypeHandler(AtomicInteger.class).toString()) - .isEqualTo("type=" + AtomicInteger.class); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, + CityMapperRepositoryConfiguration.class) + .withPropertyValues("mybatis.config-location:mybatis-config-settings-only.xml", + "mybatis.type-handlers-package:org.mybatis.spring.boot.autoconfigure.handler.") + .run(context -> { + org.apache.ibatis.session.Configuration configuration = context.getBean(SqlSessionFactory.class) + .getConfiguration(); + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBeanNamesForType(CityMapper.class)).hasSize(1); + assertThat(configuration.getDefaultFetchSize()).isEqualTo(1000); + assertThat(configuration.getTypeHandlerRegistry().getTypeHandler(BigInteger.class)) + .isInstanceOf(DummyTypeHandler.class); + assertThat(configuration.getTypeHandlerRegistry().getTypeHandler(AtomicInteger.class)) + .isInstanceOf(AtomicNumberTypeHandler.class); + assertThat(configuration.getTypeHandlerRegistry().getTypeHandler(AtomicLong.class)) + .isInstanceOf(AtomicNumberTypeHandler.class); + assertThat(configuration.getTypeHandlerRegistry().getTypeHandler(AtomicInteger.class)) + .hasToString("type=" + AtomicInteger.class); + }); } @Test void testMixedWithConfigurationFileAndTypeAliasesPackageAndMapperLocations() { - TestPropertyValues - .of("mybatis.config-location:mybatis-config-settings-only.xml", + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, + CityMapperRepositoryConfiguration.class) + .withPropertyValues("mybatis.config-location:mybatis-config-settings-only.xml", "mybatis.type-aliases-package:org.mybatis.spring.boot.autoconfigure.domain", "mybatis.mapper-locations:classpath:org/mybatis/spring/boot/autoconfigure/repository/CityMapper.xml") - .applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class); - this.context.refresh(); - - org.apache.ibatis.session.Configuration configuration = this.context.getBean(SqlSessionFactory.class) - .getConfiguration(); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(CityMapper.class)).hasSize(1); - assertThat(configuration.getDefaultFetchSize()).isEqualTo(1000); - assertThat(configuration.getMappedStatementNames()).contains("selectCityById"); - assertThat(configuration.getMappedStatementNames()) - .contains("org.mybatis.spring.boot.autoconfigure.repository.CityMapperImpl.selectCityById"); - assertThat(configuration.getTypeAliasRegistry().getTypeAliases()).containsKey("city"); - assertThat(configuration.getTypeAliasRegistry().getTypeAliases()).containsKey("name"); + .run(context -> { + org.apache.ibatis.session.Configuration configuration = context.getBean(SqlSessionFactory.class) + .getConfiguration(); + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBeanNamesForType(CityMapper.class)).hasSize(1); + assertThat(configuration.getDefaultFetchSize()).isEqualTo(1000); + assertThat(configuration.getMappedStatementNames()).contains("selectCityById"); + assertThat(configuration.getMappedStatementNames()) + .contains("org.mybatis.spring.boot.autoconfigure.repository.CityMapperImpl.selectCityById"); + assertThat(configuration.getTypeAliasRegistry().getTypeAliases()).containsKey("city"); + assertThat(configuration.getTypeAliasRegistry().getTypeAliases()).containsKey("name"); + }); } @Test void testMixedWithFullConfigurations() { - TestPropertyValues.of("mybatis.config-location:mybatis-config-settings-only.xml", - "mybatis.type-handlers-package:org.mybatis.spring.**.handler", - "mybatis.type-aliases-package:org.mybatis.spring.boot.autoconfigure.domain", - "mybatis.mapper-locations:classpath:org/mybatis/spring/boot/autoconfigure/repository/CityMapper.xml", - "mybatis.executor-type=REUSE").applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, - MybatisInterceptorConfiguration.class, DatabaseProvidersConfiguration.class); - this.context.refresh(); - - org.apache.ibatis.session.Configuration configuration = this.context.getBean(SqlSessionFactory.class) - .getConfiguration(); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(CityMapper.class)).hasSize(1); - assertThat(configuration.getDefaultFetchSize()).isEqualTo(1000); - assertThat(configuration.getTypeHandlerRegistry().getTypeHandler(BigInteger.class)) - .isInstanceOf(DummyTypeHandler.class); - assertThat(configuration.getTypeHandlerRegistry().getTypeHandler(AtomicInteger.class)) - .isInstanceOf(AtomicNumberTypeHandler.class); - assertThat(configuration.getTypeHandlerRegistry().getTypeHandler(AtomicLong.class)) - .isInstanceOf(AtomicNumberTypeHandler.class); - assertThat(configuration.getMappedStatementNames()).hasSize(4); - assertThat(configuration.getMappedStatementNames()).contains("selectCityById"); - assertThat(configuration.getMappedStatementNames()) - .contains("org.mybatis.spring.boot.autoconfigure.repository.CityMapperImpl.selectCityById"); - assertThat(configuration.getMappedStatementNames()).contains("findById"); - assertThat(configuration.getMappedStatementNames()) - .contains("org.mybatis.spring.boot.autoconfigure.mapper.CityMapper.findById"); - assertThat(this.context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.REUSE); - assertThat(configuration.getInterceptors()).hasSize(2); - assertThat(configuration.getInterceptors().get(0)).isInstanceOf(MyInterceptor2.class); - assertThat(configuration.getInterceptors().get(1)).isInstanceOf(MyInterceptor.class); - assertThat(configuration.getDatabaseId()).isEqualTo("h2"); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, + MybatisInterceptorConfiguration.class, DatabaseProvidersConfiguration.class, + CityMapperRepositoryConfiguration.class) + .withPropertyValues("mybatis.config-location:mybatis-config-settings-only.xml", + "mybatis.type-handlers-package:org.mybatis.spring.**.handler", + "mybatis.type-aliases-package:org.mybatis.spring.boot.autoconfigure.domain", + "mybatis.mapper-locations:classpath:org/mybatis/spring/boot/autoconfigure/repository/CityMapper.xml", + "mybatis.executor-type=REUSE") + .run(context -> { + org.apache.ibatis.session.Configuration configuration = context.getBean(SqlSessionFactory.class) + .getConfiguration(); + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBeanNamesForType(CityMapper.class)).hasSize(1); + assertThat(configuration.getDefaultFetchSize()).isEqualTo(1000); + assertThat(configuration.getTypeHandlerRegistry().getTypeHandler(BigInteger.class)) + .isInstanceOf(DummyTypeHandler.class); + assertThat(configuration.getTypeHandlerRegistry().getTypeHandler(AtomicInteger.class)) + .isInstanceOf(AtomicNumberTypeHandler.class); + assertThat(configuration.getTypeHandlerRegistry().getTypeHandler(AtomicLong.class)) + .isInstanceOf(AtomicNumberTypeHandler.class); + assertThat(configuration.getMappedStatementNames()).hasSize(4); + assertThat(configuration.getMappedStatementNames()).contains("selectCityById"); + assertThat(configuration.getMappedStatementNames()) + .contains("org.mybatis.spring.boot.autoconfigure.repository.CityMapperImpl.selectCityById"); + assertThat(configuration.getMappedStatementNames()).contains("findById"); + assertThat(configuration.getMappedStatementNames()) + .contains("org.mybatis.spring.boot.autoconfigure.mapper.CityMapper.findById"); + assertThat(context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.REUSE); + assertThat(configuration.getInterceptors()).hasSize(2); + assertThat(configuration.getInterceptors().get(0)).isInstanceOf(MyInterceptor2.class); + assertThat(configuration.getInterceptors().get(1)).isInstanceOf(MyInterceptor.class); + assertThat(configuration.getDatabaseId()).isEqualTo("h2"); + }); } @Test void testWithMyBatisConfiguration() { - TestPropertyValues.of("mybatis.configuration.map-underscore-to-camel-case:true").applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()).isTrue(); + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) + .withPropertyValues("mybatis.configuration.map-underscore-to-camel-case:true").run(context -> assertThat( + context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()).isTrue()); } @Test void testWithMyBatisConfigurationCustomizeByJavaConfig() { - TestPropertyValues.of("mybatis.configuration.default-fetch-size:100").applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class, - MybatisPropertiesConfigurationCustomizer.class); - this.context.refresh(); - SqlSessionFactory sqlSessionFactory = this.context.getBean(SqlSessionFactory.class); - assertThat(sqlSessionFactory.getConfiguration().getDefaultFetchSize()).isEqualTo(100); - assertThat(sqlSessionFactory.getConfiguration().getTypeHandlerRegistry().getTypeHandler(BigInteger.class)) - .isInstanceOf(DummyTypeHandler.class); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisPropertiesConfigurationCustomizer.class) + .withPropertyValues("mybatis.configuration.default-fetch-size:100").run(context -> { + SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class); + assertThat(sqlSessionFactory.getConfiguration().getDefaultFetchSize()).isEqualTo(100); + assertThat(sqlSessionFactory.getConfiguration().getTypeHandlerRegistry().getTypeHandler(BigInteger.class)) + .isInstanceOf(DummyTypeHandler.class); + }); } @Test void testWithMyBatisConfigurationCustomizer() { - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class, - MyBatisConfigurationCustomizerConfiguration.class); - this.context.refresh(); - SqlSessionFactory sqlSessionFactory = this.context.getBean(SqlSessionFactory.class); - assertThat(sqlSessionFactory.getConfiguration().getTypeHandlerRegistry().getTypeHandler(BigInteger.class)) - .isInstanceOf(DummyTypeHandler.class); - assertThat(sqlSessionFactory.getConfiguration().getCache("test")).isNotNull(); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MyBatisConfigurationCustomizerConfiguration.class) + .run(context -> { + SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class); + assertThat(sqlSessionFactory.getConfiguration().getTypeHandlerRegistry().getTypeHandler(BigInteger.class)) + .isInstanceOf(DummyTypeHandler.class); + assertThat(sqlSessionFactory.getConfiguration().getCache("test")).isNotNull(); + }); } @Test void testWithSqlSessionFactoryBeanCustomizer() { - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class, - SqlSessionFactoryBeanCustomizerConfiguration.class); - this.context.refresh(); - SqlSessionFactory sqlSessionFactory = this.context.getBean(SqlSessionFactory.class); - assertThat(sqlSessionFactory.getConfiguration().getTypeHandlerRegistry().getTypeHandler(BigInteger.class)) - .isInstanceOf(DummyTypeHandler.class); - assertThat(sqlSessionFactory.getConfiguration().getCache("test")).isNotNull(); + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, + SqlSessionFactoryBeanCustomizerConfiguration.class).run(context -> { + SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class); + assertThat(sqlSessionFactory.getConfiguration().getTypeHandlerRegistry().getTypeHandler(BigInteger.class)) + .isInstanceOf(DummyTypeHandler.class); + assertThat(sqlSessionFactory.getConfiguration().getCache("test")).isNotNull(); + }); } @Test void testConfigFileAndConfigurationWithTogether() { - TestPropertyValues - .of("mybatis.config-location:mybatis-config.xml", "mybatis.configuration.default-statement-timeout:30") - .applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class); - - try { - this.context.refresh(); - fail("Should be occurred a BeanCreationException."); - } catch (BeanCreationException e) { - assertThat(e.getMessage()) - .contains("Property 'configuration' and 'configLocation' can not specified with together"); - } + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) + .withPropertyValues("mybatis.config-location:mybatis-config.xml", + "mybatis.configuration.default-statement-timeout:30") + .run(context -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) + .hasMessageContaining("Property 'configuration' and 'configLocation' can not specified with together"); + }); } @Test void testWithoutConfigurationVariablesAndProperties() { - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - - Properties variables = this.context.getBean(SqlSessionFactory.class).getConfiguration().getVariables(); - assertThat(variables).isEmpty(); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class) + .run(context -> { + Properties variables = context.getBean(SqlSessionFactory.class).getConfiguration().getVariables(); + assertThat(variables).isEmpty(); + }); } @Test void testWithConfigurationVariablesOnly() { - TestPropertyValues.of("mybatis.configuration.variables.key1:value1").applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - - Properties variables = this.context.getBean(SqlSessionFactory.class).getConfiguration().getVariables(); - assertThat(variables).hasSize(1); - assertThat(variables.getProperty("key1")).isEqualTo("value1"); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class) + .withPropertyValues("mybatis.configuration.variables.key1:value1").run(context -> { + Properties variables = context.getBean(SqlSessionFactory.class).getConfiguration().getVariables(); + assertThat(variables).hasSize(1); + assertThat(variables.getProperty("key1")).isEqualTo("value1"); + }); } @Test void testWithConfigurationPropertiesOnly() { - TestPropertyValues.of("mybatis.configuration-properties.key2:value2").applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - - Properties variables = this.context.getBean(SqlSessionFactory.class).getConfiguration().getVariables(); - assertThat(variables).hasSize(1); - assertThat(variables.getProperty("key2")).isEqualTo("value2"); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class) + .withPropertyValues("mybatis.configuration-properties.key2:value2").run(context -> { + Properties variables = context.getBean(SqlSessionFactory.class).getConfiguration().getVariables(); + assertThat(variables).hasSize(1); + assertThat(variables.getProperty("key2")).isEqualTo("value2"); + }); } @Test void testWithConfigurationVariablesAndPropertiesOtherKey() { - TestPropertyValues.of("mybatis.configuration.variables.key1:value1", "mybatis.configuration-properties.key2:value2") - .applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - - Properties variables = this.context.getBean(SqlSessionFactory.class).getConfiguration().getVariables(); - assertThat(variables).hasSize(2); - assertThat(variables.getProperty("key1")).isEqualTo("value1"); - assertThat(variables.getProperty("key2")).isEqualTo("value2"); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class) + .withPropertyValues("mybatis.configuration.variables.key1:value1", + "mybatis.configuration-properties.key2:value2") + .run(context -> { + Properties variables = context.getBean(SqlSessionFactory.class).getConfiguration().getVariables(); + assertThat(variables).hasSize(2); + assertThat(variables.getProperty("key1")).isEqualTo("value1"); + assertThat(variables.getProperty("key2")).isEqualTo("value2"); + }); } @Test void testWithConfigurationVariablesAndPropertiesSameKey() { - TestPropertyValues.of("mybatis.configuration.variables.key:value1", "mybatis.configuration-properties.key:value2") - .applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - - Properties variables = this.context.getBean(SqlSessionFactory.class).getConfiguration().getVariables(); - assertThat(variables).hasSize(1); - assertThat(variables.getProperty("key")).isEqualTo("value2"); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class) + .withPropertyValues("mybatis.configuration.variables.key:value1", "mybatis.configuration-properties.key:value2") + .run(context -> { + Properties variables = context.getBean(SqlSessionFactory.class).getConfiguration().getVariables(); + assertThat(variables).hasSize(1); + assertThat(variables.getProperty("key")).isEqualTo("value2"); + }); } @Test void testCustomSqlSessionFactory() { - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, - CustomSqlSessionFactoryConfiguration.class, MybatisAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().getVariables().getProperty("key")) - .isEqualTo("value"); - assertThat(this.context.getBeanNamesForType(CityMapper.class)).hasSize(1); - assertThat(((RuntimeBeanReference) this.context.getBeanDefinition("cityMapper").getPropertyValues() - .getPropertyValue("sqlSessionFactory").getValue()).getBeanName()).isEqualTo("customSqlSessionFactory"); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, + CustomSqlSessionFactoryConfiguration.class, CityMapperRepositoryConfiguration.class) + .run(context -> { + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().getVariables().getProperty("key")) + .isEqualTo("value"); + assertThat(context.getBeanNamesForType(CityMapper.class)).hasSize(1); + assertThat(((RuntimeBeanReference) context.getBeanFactory().getBeanDefinition("cityMapper") + .getPropertyValues().getPropertyValue("sqlSessionFactory").getValue()).getBeanName()) + .isEqualTo("customSqlSessionFactory"); + }); } @Test void testMySqlSessionFactory() { - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class, - MySqlSessionFactoryConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionFactory.class)).isInstanceOf(MySqlSessionFactory.class); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MySqlSessionFactoryConfiguration.class) + .run(context -> { + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBean(SqlSessionFactory.class)).isInstanceOf(MySqlSessionFactory.class); + }); } @Test void testCustomSqlSessionTemplate() { - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, - CustomSqlSessionTemplateConfiguration.class, MybatisAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.BATCH); - assertThat(this.context.getBeanNamesForType(CityMapper.class)).hasSize(1); - assertThat(((RuntimeBeanReference) this.context.getBeanDefinition("cityMapper").getPropertyValues() - .getPropertyValue("sqlSessionTemplate").getValue()).getBeanName()).isEqualTo("customSqlSessionTemplate"); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, + CustomSqlSessionTemplateConfiguration.class, CityMapperRepositoryConfiguration.class) + .run(context -> { + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.BATCH); + assertThat(context.getBeanNamesForType(CityMapper.class)).hasSize(1); + assertThat(((RuntimeBeanReference) context.getBeanFactory().getBeanDefinition("cityMapper") + .getPropertyValues().getPropertyValue("sqlSessionTemplate").getValue()).getBeanName()) + .isEqualTo("customSqlSessionTemplate"); + }); } @Test void testMySqlSessionTemplate() { - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class, - MySqlSessionTemplateConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionTemplate.class)).isInstanceOf(MySqlSessionTemplate.class); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MySqlSessionTemplateConfiguration.class) + .run(context -> { + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBean(SqlSessionTemplate.class)).isInstanceOf(MySqlSessionTemplate.class); + }); } @Test void testCustomSqlSessionTemplateAndSqlSessionFactory() { - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, - CustomSqlSessionFactoryConfiguration.class, CustomSqlSessionTemplateConfiguration.class, - MybatisAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.BATCH); - assertThat(this.context.getBeanNamesForType(CityMapper.class)).hasSize(1); - assertThat(((RuntimeBeanReference) this.context.getBeanDefinition("cityMapper").getPropertyValues() - .getPropertyValue("sqlSessionTemplate").getValue()).getBeanName()).isEqualTo("customSqlSessionTemplate"); + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, + MybatisBootMapperScanAutoConfiguration.class, CustomSqlSessionFactoryConfiguration.class, + CustomSqlSessionTemplateConfiguration.class, CityMapperRepositoryConfiguration.class).run(context -> { + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.BATCH); + assertThat(context.getBeanNamesForType(CityMapper.class)).hasSize(1); + assertThat(((RuntimeBeanReference) context.getBeanFactory().getBeanDefinition("cityMapper") + .getPropertyValues().getPropertyValue("sqlSessionTemplate").getValue()).getBeanName()) + .isEqualTo("customSqlSessionTemplate"); + }); } @Test void testTypeAliasesSuperTypeIsSpecify() { - TestPropertyValues - .of("mybatis.type-aliases-package:org.mybatis.spring.boot.autoconfigure.domain", + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class) + .withPropertyValues("mybatis.type-aliases-package:org.mybatis.spring.boot.autoconfigure.domain", "mybatis.type-aliases-super-type:org.mybatis.spring.boot.autoconfigure.domain.Domain") - .applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class); - this.context.refresh(); - - org.apache.ibatis.session.Configuration configuration = this.context.getBean(SqlSessionFactory.class) - .getConfiguration(); - assertThat(configuration.getTypeAliasRegistry().getTypeAliases()).containsKey("city"); - assertThat(configuration.getTypeAliasRegistry().getTypeAliases()).doesNotContainKey("name"); + .run(context -> { + org.apache.ibatis.session.Configuration configuration = context.getBean(SqlSessionFactory.class) + .getConfiguration(); + assertThat(configuration.getTypeAliasRegistry().getTypeAliases()).containsKey("city"); + assertThat(configuration.getTypeAliasRegistry().getTypeAliases()).doesNotContainKey("name"); + }); } @Test void testMapperFactoryBean() { - this.context.register(EmbeddedDataSourceConfiguration.class, MapperFactoryBeanConfiguration.class, - MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - SqlSessionFactory sqlSessionFactory = this.context.getBean(SqlSessionFactory.class); - assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(DateTimeMapper.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.SIMPLE); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()).isFalse(); + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, + MapperFactoryBeanConfiguration.class, PropertyPlaceholderAutoConfiguration.class).run(context -> { + SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class); + assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBeanNamesForType(DateTimeMapper.class)).hasSize(1); + assertThat(context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.SIMPLE); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()) + .isFalse(); + }); } @Test void testMapperScannerConfigurer() { - this.context.register(EmbeddedDataSourceConfiguration.class, MapperScannerConfigurerConfiguration.class, - MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - SqlSessionFactory sqlSessionFactory = this.context.getBean(SqlSessionFactory.class); - assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(DateTimeMapper.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.SIMPLE); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()).isFalse(); + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, + MapperScannerConfigurerConfiguration.class, PropertyPlaceholderAutoConfiguration.class).run(context -> { + SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class); + assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBeanNamesForType(DateTimeMapper.class)).hasSize(1); + assertThat(context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.SIMPLE); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()) + .isFalse(); + }); } @Test void testDefaultScriptingLanguageIsSpecify() { - TestPropertyValues - .of("mybatis.default-scripting-language-driver:org.mybatis.scripting.thymeleaf.ThymeleafLanguageDriver") - .applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisScanMapperConfiguration.class, - MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - SqlSessionFactory sqlSessionFactory = this.context.getBean(SqlSessionFactory.class); - LanguageDriverRegistry languageDriverRegistry = sqlSessionFactory.getConfiguration().getLanguageRegistry(); - assertThat(languageDriverRegistry.getDefaultDriverClass()).isEqualTo(ThymeleafLanguageDriver.class); - assertThat(languageDriverRegistry.getDefaultDriver()).isInstanceOf(ThymeleafLanguageDriver.class); - assertThat(languageDriverRegistry.getDriver(ThymeleafLanguageDriver.class)).isNotNull(); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisScanMapperConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .withPropertyValues( + "mybatis.default-scripting-language-driver:org.mybatis.scripting.thymeleaf.ThymeleafLanguageDriver") + .run(context -> { + SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class); + LanguageDriverRegistry languageDriverRegistry = sqlSessionFactory.getConfiguration().getLanguageRegistry(); + assertThat(languageDriverRegistry.getDefaultDriverClass()).isEqualTo(ThymeleafLanguageDriver.class); + assertThat(languageDriverRegistry.getDefaultDriver()).isInstanceOf(ThymeleafLanguageDriver.class); + assertThat(languageDriverRegistry.getDriver(ThymeleafLanguageDriver.class)).isNotNull(); + }); } @Test void testExcludeMybatisLanguageDriverAutoConfiguration() { - TestPropertyValues - .of("spring.autoconfigure.exclude:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration") - .applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisScanMapperConfiguration.class, - MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - SqlSessionFactory sqlSessionFactory = this.context.getBean(SqlSessionFactory.class); - assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); - assertThat(this.context.getBeanNamesForType(DateTimeMapper.class)).hasSize(1); - assertThat(this.context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.SIMPLE); - assertThat(this.context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()).isFalse(); - assertThat(this.context.getBeanNamesForType(LanguageDriver.class)).hasSize(0); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisScanMapperConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .withPropertyValues( + "spring.autoconfigure.exclude:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration") + .run(context -> { + SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class); + assertThat(sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers()).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); + assertThat(context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); + assertThat(context.getBeanNamesForType(DateTimeMapper.class)).hasSize(1); + assertThat(context.getBean(SqlSessionTemplate.class).getExecutorType()).isEqualTo(ExecutorType.SIMPLE); + assertThat(context.getBean(SqlSessionFactory.class).getConfiguration().isMapUnderscoreToCamelCase()) + .isFalse(); + assertThat(context.getBeanNamesForType(LanguageDriver.class)).hasSize(0); + }); } @Test void testMybatisLanguageDriverAutoConfigurationWithSingleCandidate() { - TestPropertyValues - .of("spring.autoconfigure.exclude:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration") - .applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisScanMapperConfiguration.class, - SingleLanguageDriverConfiguration.class, MybatisAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - SqlSessionFactory sqlSessionFactory = this.context.getBean(SqlSessionFactory.class); - LanguageDriverRegistry languageDriverRegistry = sqlSessionFactory.getConfiguration().getLanguageRegistry(); - assertThat(this.context.getBeanNamesForType(LanguageDriver.class)).hasSize(1); - assertThat(languageDriverRegistry.getDefaultDriverClass()).isEqualTo(ThymeleafLanguageDriver.class); - assertThat(languageDriverRegistry.getDefaultDriver()).isInstanceOf(ThymeleafLanguageDriver.class); - assertThat(languageDriverRegistry.getDriver(ThymeleafLanguageDriver.class)).isNotNull(); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisScanMapperConfiguration.class, + SingleLanguageDriverConfiguration.class, PropertyPlaceholderAutoConfiguration.class) + .withPropertyValues( + "spring.autoconfigure.exclude:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration") + .run(context -> { + SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class); + LanguageDriverRegistry languageDriverRegistry = sqlSessionFactory.getConfiguration().getLanguageRegistry(); + assertThat(context.getBeanNamesForType(LanguageDriver.class)).hasSize(1); + assertThat(languageDriverRegistry.getDefaultDriverClass()).isEqualTo(ThymeleafLanguageDriver.class); + assertThat(languageDriverRegistry.getDefaultDriver()).isInstanceOf(ThymeleafLanguageDriver.class); + assertThat(languageDriverRegistry.getDriver(ThymeleafLanguageDriver.class)).isNotNull(); + }); } @Test void testMybatisLanguageDriverAutoConfigurationWithSingleCandidateWhenDefaultLanguageDriverIsSpecify() { - TestPropertyValues - .of("mybatis.default-scripting-language-driver:org.apache.ibatis.scripting.xmltags.XMLLanguageDriver", + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MybatisScanMapperConfiguration.class, + SingleLanguageDriverConfiguration.class, PropertyPlaceholderAutoConfiguration.class) + .withPropertyValues( + "mybatis.default-scripting-language-driver:org.apache.ibatis.scripting.xmltags.XMLLanguageDriver", "spring.autoconfigure.exclude:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration") - .applyTo(this.context); - this.context.register(EmbeddedDataSourceConfiguration.class, MybatisScanMapperConfiguration.class, - SingleLanguageDriverConfiguration.class, MybatisAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - this.context.refresh(); - SqlSessionFactory sqlSessionFactory = this.context.getBean(SqlSessionFactory.class); - LanguageDriverRegistry languageDriverRegistry = sqlSessionFactory.getConfiguration().getLanguageRegistry(); - assertThat(this.context.getBeanNamesForType(LanguageDriver.class)).hasSize(1); - assertThat(languageDriverRegistry.getDefaultDriverClass()).isEqualTo(XMLLanguageDriver.class); - assertThat(languageDriverRegistry.getDefaultDriver()).isInstanceOf(XMLLanguageDriver.class); - assertThat(languageDriverRegistry.getDriver(ThymeleafLanguageDriver.class)).isNotNull(); + .run(context -> { + SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class); + LanguageDriverRegistry languageDriverRegistry = sqlSessionFactory.getConfiguration().getLanguageRegistry(); + assertThat(context.getBeanNamesForType(LanguageDriver.class)).hasSize(1); + assertThat(languageDriverRegistry.getDefaultDriverClass()).isEqualTo(XMLLanguageDriver.class); + assertThat(languageDriverRegistry.getDefaultDriver()).isInstanceOf(XMLLanguageDriver.class); + assertThat(languageDriverRegistry.getDriver(ThymeleafLanguageDriver.class)).isNotNull(); + }); } @Test @@ -907,13 +901,11 @@ DataSource dataSourceReplica() { } @Configuration - @EnableAutoConfiguration @MapperScan(basePackages = "com.example.mapper", lazyInitialization = "${mybatis.lazy-initialization:false}") static class MybatisScanMapperConfiguration { } @Configuration - @EnableAutoConfiguration static class MapperFactoryBeanConfiguration { @Bean MapperFactoryBean dateTimeMapper(SqlSessionFactory sqlSessionFactory) { @@ -924,7 +916,6 @@ MapperFactoryBean dateTimeMapper(SqlSessionFactory sqlSessionFac } @Configuration - @EnableAutoConfiguration static class MapperScannerConfigurerConfiguration { @Bean static MapperScannerConfigurer mapperScannerConfigurer() { @@ -935,7 +926,6 @@ static MapperScannerConfigurer mapperScannerConfigurer() { } @Configuration - @EnableAutoConfiguration static class MybatisBootMapperScanAutoConfiguration implements BeanFactoryPostProcessor { @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { @@ -944,7 +934,6 @@ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) } @Configuration - @EnableAutoConfiguration static class MybatisMapperConfiguration { @Bean @@ -955,7 +944,6 @@ public CityMapperImpl cityMapper() { } @Configuration - @EnableAutoConfiguration static class MybatisInterceptorConfiguration { @Bean @@ -973,7 +961,6 @@ public MyInterceptor2 myInterceptor2() { } @Configuration - @EnableAutoConfiguration static class MybatisInterceptorConfiguration2 { @Bean @@ -991,7 +978,6 @@ public MyInterceptor2 myInterceptor2() { } @Configuration - @EnableAutoConfiguration static class MybatisTypeHandlerConfiguration { @Bean @@ -1002,7 +988,6 @@ public MyTypeHandler myTypeHandler() { } @Configuration - @EnableAutoConfiguration static class MybatisPropertiesConfigurationCustomizer { @Autowired void customize(MybatisProperties properties) { @@ -1011,7 +996,6 @@ void customize(MybatisProperties properties) { } @Configuration - @EnableAutoConfiguration static class MyBatisConfigurationCustomizerConfiguration { @Bean ConfigurationCustomizer typeHandlerConfigurationCustomizer() { @@ -1025,7 +1009,6 @@ ConfigurationCustomizer cacheConfigurationCustomizer() { } @Configuration - @EnableAutoConfiguration static class SqlSessionFactoryBeanCustomizerConfiguration { @Bean SqlSessionFactoryBeanCustomizer typeHandlerSqlSessionFactoryBeanCustomizer() { @@ -1184,6 +1167,12 @@ public UUID getNullableResult(CallableStatement cs, int columnIndex) { } + @Configuration + @TestAutoConfigurationPackage(CityMapper.class) + static class CityMapperRepositoryConfiguration { + + } + @Configuration(proxyBeanMethods = false) static class CustomFlywayMigrationInitializer { diff --git a/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/MybatisLanguageDriverAutoConfigurationTest.java b/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/MybatisLanguageDriverAutoConfigurationTest.java index b1e50360d..e5780af4f 100644 --- a/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/MybatisLanguageDriverAutoConfigurationTest.java +++ b/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/MybatisLanguageDriverAutoConfigurationTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2021 the original author or authors. + * Copyright 2015-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,20 +34,16 @@ import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.directive.Directive; import org.apache.velocity.runtime.parser.node.Node; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mybatis.scripting.freemarker.FreeMarkerLanguageDriver; import org.mybatis.scripting.freemarker.FreeMarkerLanguageDriverConfig; import org.mybatis.scripting.thymeleaf.TemplateEngineCustomizer; import org.mybatis.scripting.thymeleaf.ThymeleafLanguageDriver; import org.mybatis.scripting.thymeleaf.ThymeleafLanguageDriverConfig; -import org.mybatis.scripting.velocity.VelocityFacade; import org.mybatis.scripting.velocity.VelocityLanguageDriver; import org.mybatis.scripting.velocity.VelocityLanguageDriverConfig; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.thymeleaf.TemplateEngine; @@ -55,180 +51,171 @@ * Tests for {@link MybatisLanguageDriverAutoConfiguration}. * * @author Kazuki Shimizu + * @author Eddú Meléndez */ class MybatisLanguageDriverAutoConfigurationTest { - private AnnotationConfigApplicationContext context; - - @BeforeEach - void init() { - VelocityFacade.destroy(); - this.context = new AnnotationConfigApplicationContext(); - } - - @AfterEach - void closeContext() { - if (this.context != null) { - this.context.close(); - } - VelocityFacade.destroy(); - } + private ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(MybatisLanguageDriverAutoConfiguration.class)); @Test void testDefaultConfiguration() { - this.context.register(MybatisLanguageDriverAutoConfiguration.class); - this.context.refresh(); - Map languageDriverBeans = this.context.getBeansOfType(LanguageDriver.class); - assertThat(languageDriverBeans).hasSize(3).containsKeys("freeMarkerLanguageDriver", "velocityLanguageDriver", - "thymeleafLanguageDriver"); - assertThat(languageDriverBeans.get("freeMarkerLanguageDriver")).isInstanceOf(FreeMarkerLanguageDriver.class); - assertThat(languageDriverBeans.get("velocityLanguageDriver")).isInstanceOf(VelocityLanguageDriver.class); - assertThat(languageDriverBeans.get("thymeleafLanguageDriver")).isInstanceOf(ThymeleafLanguageDriver.class); - { - ThymeleafLanguageDriverConfig config = this.context.getBean(ThymeleafLanguageDriverConfig.class); - assertThat(config.isUse2way()).isEqualTo(true); - assertThat(config.getDialect().getPrefix()).isEqualTo("mb"); - assertThat(config.getDialect().getLikeAdditionalEscapeTargetChars()).isNull(); - assertThat(config.getDialect().getLikeEscapeChar()).isEqualTo('\\'); - assertThat(config.getDialect().getLikeEscapeClauseFormat()).isEqualTo("ESCAPE '%s'"); - assertThat(config.getTemplateFile().getBaseDir()).isEqualTo(""); - assertThat(config.getTemplateFile().getCacheTtl()).isNull(); - assertThat(config.getTemplateFile().getEncoding()).isEqualTo(StandardCharsets.UTF_8); - assertThat(config.getTemplateFile().getPatterns()).hasSize(1).contains("*.sql"); - assertThat(config.getCustomizer()).isNull(); - } - { - FreeMarkerLanguageDriverConfig config = this.context.getBean(FreeMarkerLanguageDriverConfig.class); - assertThat(config.getBasePackage()).isEqualTo(""); - assertThat(config.getFreemarkerSettings()).isEmpty(); - } - { - VelocityLanguageDriverConfig config = this.context.getBean(VelocityLanguageDriverConfig.class); + this.contextRunner.run(context -> { + Map languageDriverBeans = context.getBeansOfType(LanguageDriver.class); + assertThat(languageDriverBeans).hasSize(3).containsKeys("freeMarkerLanguageDriver", "velocityLanguageDriver", + "thymeleafLanguageDriver"); + assertThat(languageDriverBeans.get("freeMarkerLanguageDriver")).isInstanceOf(FreeMarkerLanguageDriver.class); + assertThat(languageDriverBeans.get("velocityLanguageDriver")).isInstanceOf(VelocityLanguageDriver.class); + assertThat(languageDriverBeans.get("thymeleafLanguageDriver")).isInstanceOf(ThymeleafLanguageDriver.class); + + ThymeleafLanguageDriverConfig thymeleafLanguageDriverConfig = context + .getBean(ThymeleafLanguageDriverConfig.class); + assertThat(thymeleafLanguageDriverConfig.isUse2way()).isTrue(); + assertThat(thymeleafLanguageDriverConfig.getDialect().getPrefix()).isEqualTo("mb"); + assertThat(thymeleafLanguageDriverConfig.getDialect().getLikeAdditionalEscapeTargetChars()).isNull(); + assertThat(thymeleafLanguageDriverConfig.getDialect().getLikeEscapeChar()).isEqualTo('\\'); + assertThat(thymeleafLanguageDriverConfig.getDialect().getLikeEscapeClauseFormat()).isEqualTo("ESCAPE '%s'"); + assertThat(thymeleafLanguageDriverConfig.getTemplateFile().getBaseDir()).isEmpty(); + assertThat(thymeleafLanguageDriverConfig.getTemplateFile().getCacheTtl()).isNull(); + assertThat(thymeleafLanguageDriverConfig.getTemplateFile().getEncoding()).isEqualTo(StandardCharsets.UTF_8); + assertThat(thymeleafLanguageDriverConfig.getTemplateFile().getPatterns()).hasSize(1).contains("*.sql"); + assertThat(thymeleafLanguageDriverConfig.getCustomizer()).isNull(); + + FreeMarkerLanguageDriverConfig freeMarkerLanguageDriverConfig = context + .getBean(FreeMarkerLanguageDriverConfig.class); + assertThat(freeMarkerLanguageDriverConfig.getBasePackage()).isEmpty(); + assertThat(freeMarkerLanguageDriverConfig.getFreemarkerSettings()).isEmpty(); + + VelocityLanguageDriverConfig velocityLanguageDriverConfig = context.getBean(VelocityLanguageDriverConfig.class); @SuppressWarnings("deprecation") - String[] userDirective = config.getUserdirective(); - assertThat(userDirective).hasSize(0); - assertThat(config.getAdditionalContextAttributes()).hasSize(0); - assertThat(config.getVelocitySettings()).hasSize(2); - assertThat(config.getVelocitySettings().get(RuntimeConstants.RESOURCE_LOADERS)).isEqualTo("class"); - assertThat(config.getVelocitySettings().get(RuntimeConstants.RESOURCE_LOADER + ".class.class")) - .isEqualTo("org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); - assertThat(config.generateCustomDirectivesString()).isEqualTo( + String[] userDirective = velocityLanguageDriverConfig.getUserdirective(); + assertThat(userDirective).isEmpty(); + assertThat(velocityLanguageDriverConfig.getAdditionalContextAttributes()).isEmpty(); + assertThat(velocityLanguageDriverConfig.getVelocitySettings()).hasSize(2); + assertThat(velocityLanguageDriverConfig.getVelocitySettings()).containsEntry(RuntimeConstants.RESOURCE_LOADERS, + "class"); + assertThat(velocityLanguageDriverConfig.getVelocitySettings()).containsEntry( + RuntimeConstants.RESOURCE_LOADER + ".class.class", + "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + assertThat(velocityLanguageDriverConfig.generateCustomDirectivesString()).isEqualTo( "org.mybatis.scripting.velocity.TrimDirective,org.mybatis.scripting.velocity.WhereDirective,org.mybatis.scripting.velocity.SetDirective,org.mybatis.scripting.velocity.InDirective,org.mybatis.scripting.velocity.RepeatDirective"); - } + }); } @Test void testCustomConfiguration() { - this.context.register(MyLanguageDriverConfig.class, MybatisLanguageDriverAutoConfiguration.class); - this.context.refresh(); - Map languageDriverBeans = this.context.getBeansOfType(LanguageDriver.class); - assertThat(languageDriverBeans).hasSize(3).containsKeys("myFreeMarkerLanguageDriver", "myVelocityLanguageDriver", - "myThymeleafLanguageDriver"); + this.contextRunner.withUserConfiguration(MyLanguageDriverConfig.class) + .run(context -> { + Map languageDriverBeans = context.getBeansOfType(LanguageDriver.class); + assertThat(languageDriverBeans).hasSize(3).containsKeys("myFreeMarkerLanguageDriver", + "myVelocityLanguageDriver", "myThymeleafLanguageDriver"); + }); } @Test @SuppressWarnings("deprecation") void testLegacyConfiguration() { - this.context.register(TestingLegacyFreeMarkerConfiguration.class, TestingLegacyVelocityConfiguration.class); - this.context.refresh(); - Map languageDriverBeans = this.context.getBeansOfType(LanguageDriver.class); - assertThat(languageDriverBeans).hasSize(2).containsKeys("freeMarkerLanguageDriver", "velocityLanguageDriver"); - assertThat(this.context.getBean(org.mybatis.scripting.velocity.Driver.class)).isNotNull(); - assertThat(this.context.getBean(FreeMarkerLanguageDriver.class)).isNotNull(); - assertThat(this.context.getBeanNamesForType(VelocityLanguageDriverConfig.class)).hasSize(0); - assertThat(this.context.getBeanNamesForType(FreeMarkerLanguageDriverConfig.class)).hasSize(0); + new ApplicationContextRunner() + .withUserConfiguration(TestingLegacyFreeMarkerConfiguration.class, TestingLegacyVelocityConfiguration.class) + .run(context -> { + Map languageDriverBeans = context.getBeansOfType(LanguageDriver.class); + assertThat(languageDriverBeans).hasSize(2).containsKeys("freeMarkerLanguageDriver", "velocityLanguageDriver"); + assertThat(context.getBean(org.mybatis.scripting.velocity.Driver.class)).isNotNull(); + assertThat(context.getBean(FreeMarkerLanguageDriver.class)).isNotNull(); + assertThat(context.getBeanNamesForType(VelocityLanguageDriverConfig.class)).isEmpty(); + assertThat(context.getBeanNamesForType(FreeMarkerLanguageDriverConfig.class)).isEmpty(); + }); } @Test void testCustomThymeleafConfig() { - this.context.register(ThymeleafCustomLanguageDriverConfig.class, MybatisLanguageDriverAutoConfiguration.class); - this.context.refresh(); - ThymeleafLanguageDriver driver = this.context.getBean(ThymeleafLanguageDriver.class); - SqlSource sqlSource = driver.createSqlSource(new Configuration(), - "SELECT * FROM users WHERE id = /*[# m:p='id']*/ 1 /*[/]*/", Integer.class); - BoundSql boundSql = sqlSource.getBoundSql(10); - assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ?"); - assertThat(boundSql.getParameterObject()).isEqualTo(10); - assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id"); - assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class); - ThymeleafLanguageDriverConfig config = this.context.getBean(ThymeleafLanguageDriverConfig.class); - assertThat(config.isUse2way()).isEqualTo(true); - assertThat(config.getDialect().getPrefix()).isEqualTo("m"); - assertThat(config.getDialect().getLikeAdditionalEscapeTargetChars()).isNull(); - assertThat(config.getDialect().getLikeEscapeChar()).isEqualTo('\\'); - assertThat(config.getDialect().getLikeEscapeClauseFormat()).isEqualTo("ESCAPE '%s'"); - assertThat(config.getTemplateFile().getBaseDir()).isEqualTo(""); - assertThat(config.getTemplateFile().getCacheTtl()).isNull(); - assertThat(config.getTemplateFile().getEncoding()).isEqualTo(StandardCharsets.UTF_8); - assertThat(config.getTemplateFile().getPatterns()).hasSize(1).contains("*.sql"); - assertThat(config.getCustomizer()).isNull(); - } - - @Test - void test() { - this.context.register(FreeMarkerCustomLanguageDriverConfig.class, MybatisLanguageDriverAutoConfiguration.class); - this.context.refresh(); + this.contextRunner + .withUserConfiguration(ThymeleafCustomLanguageDriverConfig.class) + .run(context -> { + ThymeleafLanguageDriver driver = context.getBean(ThymeleafLanguageDriver.class); + SqlSource sqlSource = driver.createSqlSource(new Configuration(), + "SELECT * FROM users WHERE id = /*[# m:p='id']*/ 1 /*[/]*/", Integer.class); + BoundSql boundSql = sqlSource.getBoundSql(10); + assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ?"); + assertThat(boundSql.getParameterObject()).isEqualTo(10); + assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id"); + assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class); + ThymeleafLanguageDriverConfig config = context.getBean(ThymeleafLanguageDriverConfig.class); + assertThat(config.isUse2way()).isTrue(); + assertThat(config.getDialect().getPrefix()).isEqualTo("m"); + assertThat(config.getDialect().getLikeAdditionalEscapeTargetChars()).isNull(); + assertThat(config.getDialect().getLikeEscapeChar()).isEqualTo('\\'); + assertThat(config.getDialect().getLikeEscapeClauseFormat()).isEqualTo("ESCAPE '%s'"); + assertThat(config.getTemplateFile().getBaseDir()).isEmpty(); + assertThat(config.getTemplateFile().getCacheTtl()).isNull(); + assertThat(config.getTemplateFile().getEncoding()).isEqualTo(StandardCharsets.UTF_8); + assertThat(config.getTemplateFile().getPatterns()).hasSize(1).contains("*.sql"); + assertThat(config.getCustomizer()).isNull(); + }); } @Test void testCustomFreeMarkerConfig() { - this.context.register(FreeMarkerCustomLanguageDriverConfig.class, MybatisLanguageDriverAutoConfiguration.class); - this.context.refresh(); - FreeMarkerLanguageDriver driver = this.context.getBean(FreeMarkerLanguageDriver.class); - @SuppressWarnings("unused") - class Param { - private Integer id; - private Integer version; - } - Param params = new Param(); - params.id = 10; - params.version = 20; - SqlSource sqlSource = driver.createSqlSource(new Configuration(), - "SELECT * FROM users WHERE id = #{id} and version = <@p name='version'/>", Param.class); - BoundSql boundSql = sqlSource.getBoundSql(params); - assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ? and version = ?"); - assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id"); - assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class); - assertThat(boundSql.getParameterMappings().get(1).getProperty()).isEqualTo("version"); - assertThat(boundSql.getParameterMappings().get(1).getJavaType()).isEqualTo(Integer.class); - FreeMarkerLanguageDriverConfig config = this.context.getBean(FreeMarkerLanguageDriverConfig.class); - assertThat(config.getBasePackage()).isEqualTo(""); - assertThat(config.getFreemarkerSettings()).hasSize(1); - assertThat(config.getFreemarkerSettings().get("interpolation_syntax")).isEqualTo("dollar"); + this.contextRunner + .withUserConfiguration(FreeMarkerCustomLanguageDriverConfig.class) + .run(context -> { + FreeMarkerLanguageDriver driver = context.getBean(FreeMarkerLanguageDriver.class); + @SuppressWarnings("unused") + class Param { + private Integer id; + private Integer version; + } + Param params = new Param(); + params.id = 10; + params.version = 20; + SqlSource sqlSource = driver.createSqlSource(new Configuration(), + "SELECT * FROM users WHERE id = #{id} and version = <@p name='version'/>", Param.class); + BoundSql boundSql = sqlSource.getBoundSql(params); + assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ? and version = ?"); + assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id"); + assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class); + assertThat(boundSql.getParameterMappings().get(1).getProperty()).isEqualTo("version"); + assertThat(boundSql.getParameterMappings().get(1).getJavaType()).isEqualTo(Integer.class); + FreeMarkerLanguageDriverConfig config = context.getBean(FreeMarkerLanguageDriverConfig.class); + assertThat(config.getBasePackage()).isEmpty(); + assertThat(config.getFreemarkerSettings()).hasSize(1); + assertThat(config.getFreemarkerSettings()).containsEntry("interpolation_syntax", "dollar"); + }); } @Test void testCustomVelocityConfig() { - this.context.register(VelocityCustomLanguageDriverConfig.class, MybatisLanguageDriverAutoConfiguration.class); - this.context.refresh(); - VelocityLanguageDriver driver = this.context.getBean(VelocityLanguageDriver.class); - @SuppressWarnings("unused") - class Param { - private Integer id; - private Integer version; - } - Param params = new Param(); - params.id = 10; - params.version = 20; - SqlSource sqlSource = driver.createSqlSource(new Configuration(), "#now()", Param.class); - BoundSql boundSql = sqlSource.getBoundSql(params); - assertThat(boundSql.getSql()).isEqualTo("SELECT CURRENT_TIMESTAMP"); - VelocityLanguageDriverConfig config = this.context.getBean(VelocityLanguageDriverConfig.class); - @SuppressWarnings("deprecation") - String[] userDirective = config.getUserdirective(); - assertThat(userDirective).hasSize(0); - assertThat(config.getAdditionalContextAttributes()).hasSize(0); - assertThat(config.getVelocitySettings()).hasSize(3); - assertThat(config.getVelocitySettings().get(RuntimeConstants.RESOURCE_LOADERS)).isEqualTo("class"); - assertThat(config.getVelocitySettings().get(RuntimeConstants.RESOURCE_LOADER + ".class.class")) - .isEqualTo("org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); - assertThat(config.generateCustomDirectivesString()).isEqualTo(NowDirective.class.getName() - + ",org.mybatis.scripting.velocity.TrimDirective,org.mybatis.scripting.velocity.WhereDirective,org.mybatis.scripting.velocity.SetDirective,org.mybatis.scripting.velocity.InDirective,org.mybatis.scripting.velocity.RepeatDirective"); + this.contextRunner.withUserConfiguration(VelocityCustomLanguageDriverConfig.class).run(context -> { + VelocityLanguageDriver driver = context.getBean(VelocityLanguageDriver.class); + @SuppressWarnings("unused") + class Param { + private Integer id; + private Integer version; + } + Param params = new Param(); + params.id = 10; + params.version = 20; + SqlSource sqlSource = driver.createSqlSource(new Configuration(), "#now()", Param.class); + BoundSql boundSql = sqlSource.getBoundSql(params); + assertThat(boundSql.getSql()).isEqualTo("SELECT CURRENT_TIMESTAMP"); + VelocityLanguageDriverConfig config = context.getBean(VelocityLanguageDriverConfig.class); + @SuppressWarnings("deprecation") + String[] userDirective = config.getUserdirective(); + assertThat(userDirective).isEmpty(); + assertThat(config.getAdditionalContextAttributes()).isEmpty(); + assertThat(config.getVelocitySettings()).hasSize(3); + assertThat(config.getVelocitySettings()).containsEntry(RuntimeConstants.RESOURCE_LOADERS, "class"); + assertThat(config.getVelocitySettings()).containsEntry(RuntimeConstants.RESOURCE_LOADER + ".class.class", + "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + assertThat(config.generateCustomDirectivesString()).isEqualTo(NowDirective.class.getName() + + ",org.mybatis.scripting.velocity.TrimDirective,org.mybatis.scripting.velocity.WhereDirective,org.mybatis.scripting.velocity.SetDirective,org.mybatis.scripting.velocity.InDirective,org.mybatis.scripting.velocity.RepeatDirective"); + }); } @Test void testCustomThymeleafConfigUsingConfigurationProperty() { - TestPropertyValues.of("mybatis.scripting-language-driver.thymeleaf.use2way=false", + this.contextRunner.withUserConfiguration(MyAutoConfiguration.class).withPropertyValues( + "mybatis.scripting-language-driver.thymeleaf.use2way=false", "mybatis.scripting-language-driver.thymeleaf.dialect.like-additional-escape-target-chars=*,?", "mybatis.scripting-language-driver.thymeleaf.dialect.like-escape-char=~", "mybatis.scripting-language-driver.thymeleaf.dialect.like-escape-clause-format=escape '%s'", @@ -244,121 +231,113 @@ void testCustomThymeleafConfigUsingConfigurationProperty() { "mybatis.scripting-language-driver.thymeleaf.template-file.path-provider.includes-mapper-name-when-separate-directory=false", "mybatis.scripting-language-driver.thymeleaf.template-file.path-provider.cache-enabled=false", "mybatis.scripting-language-driver.thymeleaf.customizer=org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfigurationTest$MyTemplateEngineCustomizer") - .applyTo(this.context); - this.context.register(MyAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class); - this.context.refresh(); - ThymeleafLanguageDriver driver = this.context.getBean(ThymeleafLanguageDriver.class); - SqlSource sqlSource = driver.createSqlSource(new Configuration(), - "SELECT * FROM users WHERE id = [# mybatis:p='id' /]", Integer.class); - BoundSql boundSql = sqlSource.getBoundSql(10); - assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ?"); - assertThat(boundSql.getParameterObject()).isEqualTo(10); - assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id"); - assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class); - ThymeleafLanguageDriverConfig config = this.context.getBean(ThymeleafLanguageDriverConfig.class); - assertThat(config.isUse2way()).isEqualTo(false); - assertThat(config.getDialect().getPrefix()).isEqualTo("mybatis"); - assertThat(config.getDialect().getLikeAdditionalEscapeTargetChars()).hasSize(2).contains('*', '?'); - assertThat(config.getDialect().getLikeEscapeChar()).isEqualTo('~'); - assertThat(config.getDialect().getLikeEscapeClauseFormat()).isEqualTo("escape '%s'"); - assertThat(config.getTemplateFile().getBaseDir()).isEqualTo("sqls"); - assertThat(config.getTemplateFile().getCacheTtl()).isEqualTo(1234); - assertThat(config.getTemplateFile().getEncoding()).isEqualTo(Charset.forName("Windows-31J")); - assertThat(config.getTemplateFile().getPatterns()).hasSize(2).contains("*.sql", "*.sqlf"); - assertThat(config.getTemplateFile().getPathProvider().getPrefix()).isEqualTo("sql/"); - assertThat(config.getTemplateFile().getPathProvider().isIncludesPackagePath()).isFalse(); - assertThat(config.getTemplateFile().getPathProvider().isSeparateDirectoryPerMapper()).isFalse(); - assertThat(config.getTemplateFile().getPathProvider().isIncludesMapperNameWhenSeparateDirectory()).isFalse(); - assertThat(config.getTemplateFile().getPathProvider().isCacheEnabled()).isFalse(); - assertThat(config.getCustomizer()).isEqualTo(MyTemplateEngineCustomizer.class); + .run(context -> { + ThymeleafLanguageDriver driver = context.getBean(ThymeleafLanguageDriver.class); + SqlSource sqlSource = driver.createSqlSource(new Configuration(), + "SELECT * FROM users WHERE id = [# mybatis:p='id' /]", Integer.class); + BoundSql boundSql = sqlSource.getBoundSql(10); + assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ?"); + assertThat(boundSql.getParameterObject()).isEqualTo(10); + assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id"); + assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class); + ThymeleafLanguageDriverConfig config = context.getBean(ThymeleafLanguageDriverConfig.class); + assertThat(config.isUse2way()).isFalse(); + assertThat(config.getDialect().getPrefix()).isEqualTo("mybatis"); + assertThat(config.getDialect().getLikeAdditionalEscapeTargetChars()).hasSize(2).contains('*', '?'); + assertThat(config.getDialect().getLikeEscapeChar()).isEqualTo('~'); + assertThat(config.getDialect().getLikeEscapeClauseFormat()).isEqualTo("escape '%s'"); + assertThat(config.getTemplateFile().getBaseDir()).isEqualTo("sqls"); + assertThat(config.getTemplateFile().getCacheTtl()).isEqualTo(1234); + assertThat(config.getTemplateFile().getEncoding()).isEqualTo(Charset.forName("Windows-31J")); + assertThat(config.getTemplateFile().getPatterns()).hasSize(2).contains("*.sql", "*.sqlf"); + assertThat(config.getTemplateFile().getPathProvider().getPrefix()).isEqualTo("sql/"); + assertThat(config.getTemplateFile().getPathProvider().isIncludesPackagePath()).isFalse(); + assertThat(config.getTemplateFile().getPathProvider().isSeparateDirectoryPerMapper()).isFalse(); + assertThat(config.getTemplateFile().getPathProvider().isIncludesMapperNameWhenSeparateDirectory()).isFalse(); + assertThat(config.getTemplateFile().getPathProvider().isCacheEnabled()).isFalse(); + assertThat(config.getCustomizer()).isEqualTo(MyTemplateEngineCustomizer.class); + }); } @Test void testCustomFreeMarkerConfigUsingConfigurationProperty() { - TestPropertyValues - .of("mybatis.scripting-language-driver.freemarker.base-package=sqls", + this.contextRunner.withUserConfiguration(MyAutoConfiguration.class) + .withPropertyValues("mybatis.scripting-language-driver.freemarker.base-package=sqls", "mybatis.scripting-language-driver.freemarker.freemarker-settings.interpolation_syntax=dollar", "mybatis.scripting-language-driver.freemarker.freemarker-settings.whitespace_stripping=yes") - .applyTo(this.context); - this.context.register(MyAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class); - this.context.refresh(); - FreeMarkerLanguageDriver driver = this.context.getBean(FreeMarkerLanguageDriver.class); - @SuppressWarnings("unused") - class Param { - private Integer id; - private Integer version; - } - Param params = new Param(); - params.id = 10; - params.version = 20; - SqlSource sqlSource = driver.createSqlSource(new Configuration(), - "SELECT * FROM users WHERE id = #{id} and version = <@p name='version'/>", Param.class); - BoundSql boundSql = sqlSource.getBoundSql(params); - assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ? and version = ?"); - assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id"); - assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class); - assertThat(boundSql.getParameterMappings().get(1).getProperty()).isEqualTo("version"); - assertThat(boundSql.getParameterMappings().get(1).getJavaType()).isEqualTo(Integer.class); - FreeMarkerLanguageDriverConfig config = this.context.getBean(FreeMarkerLanguageDriverConfig.class); - assertThat(config.getBasePackage()).isEqualTo("sqls"); - assertThat(config.getFreemarkerSettings()).hasSize(2); - assertThat(config.getFreemarkerSettings().get("interpolation_syntax")).isEqualTo("dollar"); - assertThat(config.getFreemarkerSettings().get("whitespace_stripping")).isEqualTo("yes"); + .run(context -> { + FreeMarkerLanguageDriver driver = context.getBean(FreeMarkerLanguageDriver.class); + @SuppressWarnings("unused") + class Param { + private Integer id; + private Integer version; + } + Param params = new Param(); + params.id = 10; + params.version = 20; + SqlSource sqlSource = driver.createSqlSource(new Configuration(), + "SELECT * FROM users WHERE id = #{id} and version = <@p name='version'/>", Param.class); + BoundSql boundSql = sqlSource.getBoundSql(params); + assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ? and version = ?"); + assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id"); + assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class); + assertThat(boundSql.getParameterMappings().get(1).getProperty()).isEqualTo("version"); + assertThat(boundSql.getParameterMappings().get(1).getJavaType()).isEqualTo(Integer.class); + FreeMarkerLanguageDriverConfig config = context.getBean(FreeMarkerLanguageDriverConfig.class); + assertThat(config.getBasePackage()).isEqualTo("sqls"); + assertThat(config.getFreemarkerSettings()).hasSize(2); + assertThat(config.getFreemarkerSettings()).containsEntry("interpolation_syntax", "dollar"); + assertThat(config.getFreemarkerSettings()).containsEntry("whitespace_stripping", "yes"); + }); } @Test void testCustomVelocityConfigUsingConfigurationProperty() { - TestPropertyValues - .of("mybatis.scripting-language-driver.velocity.userdirective=" + NowDirective.class.getName(), + this.contextRunner.withUserConfiguration(MyAutoConfiguration.class) + .withPropertyValues("mybatis.scripting-language-driver.velocity.userdirective=" + NowDirective.class.getName(), "mybatis.scripting-language-driver.velocity.velocity-settings." + RuntimeConstants.INPUT_ENCODING + "=" + RuntimeConstants.ENCODING_DEFAULT, "mybatis.scripting-language-driver.velocity.additional-context-attributes.attribute1=java.lang.String", "mybatis.scripting-language-driver.velocity.additional-context-attributes.attribute2=java.util.HashMap") - .applyTo(this.context); - this.context.register(MyAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class); - this.context.refresh(); - VelocityLanguageDriver driver = this.context.getBean(VelocityLanguageDriver.class); - @SuppressWarnings("unused") - class Param { - private Integer id; - private Integer version; - } - Param params = new Param(); - params.id = 10; - params.version = 20; - SqlSource sqlSource = driver.createSqlSource(new Configuration(), "#now()", Param.class); - BoundSql boundSql = sqlSource.getBoundSql(params); - assertThat(boundSql.getSql()).isEqualTo("SELECT CURRENT_TIMESTAMP"); - VelocityLanguageDriverConfig config = this.context.getBean(VelocityLanguageDriverConfig.class); - @SuppressWarnings("deprecation") - String[] userDirective = config.getUserdirective(); - assertThat(userDirective).hasSize(1).contains(NowDirective.class.getName()); - assertThat(config.getAdditionalContextAttributes()).hasSize(2); - assertThat(config.getAdditionalContextAttributes().get("attribute1")).isEqualTo("java.lang.String"); - assertThat(config.getAdditionalContextAttributes().get("attribute2")).isEqualTo("java.util.HashMap"); - assertThat(config.getVelocitySettings()).hasSize(3); - assertThat(config.getVelocitySettings().get(RuntimeConstants.RESOURCE_LOADERS)).isEqualTo("class"); - assertThat(config.getVelocitySettings().get(RuntimeConstants.RESOURCE_LOADER + ".class.class")) - .isEqualTo("org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); - assertThat(config.generateCustomDirectivesString()).isEqualTo(NowDirective.class.getName() - + ",org.mybatis.scripting.velocity.TrimDirective,org.mybatis.scripting.velocity.WhereDirective,org.mybatis.scripting.velocity.SetDirective,org.mybatis.scripting.velocity.InDirective,org.mybatis.scripting.velocity.RepeatDirective"); - assertThat(config.getVelocitySettings().get(RuntimeConstants.INPUT_ENCODING)) - .isEqualTo(RuntimeConstants.ENCODING_DEFAULT); - + .run(context -> { + VelocityLanguageDriver driver = context.getBean(VelocityLanguageDriver.class); + @SuppressWarnings("unused") + class Param { + private Integer id; + private Integer version; + } + Param params = new Param(); + params.id = 10; + params.version = 20; + SqlSource sqlSource = driver.createSqlSource(new Configuration(), "#now()", Param.class); + BoundSql boundSql = sqlSource.getBoundSql(params); + assertThat(boundSql.getSql()).isEqualTo("SELECT CURRENT_TIMESTAMP"); + VelocityLanguageDriverConfig config = context.getBean(VelocityLanguageDriverConfig.class); + @SuppressWarnings("deprecation") + String[] userDirective = config.getUserdirective(); + assertThat(userDirective).hasSize(1).contains(NowDirective.class.getName()); + assertThat(config.getAdditionalContextAttributes()).hasSize(2); + assertThat(config.getAdditionalContextAttributes()).containsEntry("attribute1", "java.lang.String"); + assertThat(config.getAdditionalContextAttributes()).containsEntry("attribute2", "java.util.HashMap"); + assertThat(config.getVelocitySettings()).hasSize(3); + assertThat(config.getVelocitySettings()).containsEntry(RuntimeConstants.RESOURCE_LOADERS, "class"); + assertThat(config.getVelocitySettings()).containsEntry(RuntimeConstants.RESOURCE_LOADER + ".class.class", + "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + assertThat(config.generateCustomDirectivesString()).isEqualTo(NowDirective.class.getName() + + ",org.mybatis.scripting.velocity.TrimDirective,org.mybatis.scripting.velocity.WhereDirective,org.mybatis.scripting.velocity.SetDirective,org.mybatis.scripting.velocity.InDirective,org.mybatis.scripting.velocity.RepeatDirective"); + assertThat(config.getVelocitySettings()).containsEntry(RuntimeConstants.INPUT_ENCODING, + RuntimeConstants.ENCODING_DEFAULT); + }); } @Test void testExcludeMybatisLanguageDriverAutoConfiguration() { - TestPropertyValues - .of("spring.autoconfigure.exclude:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration") - .applyTo(this.context); - this.context.register(MyAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBeanNamesForType(LanguageDriver.class)).hasSize(0); + new ApplicationContextRunner().withUserConfiguration(MyAutoConfiguration.class) + .run(context -> assertThat(context.getBeanNamesForType(LanguageDriver.class)).isEmpty()); } - @EnableAutoConfiguration - private static class MyAutoConfiguration { + @org.springframework.context.annotation.Configuration + static class MyAutoConfiguration { } @org.springframework.context.annotation.Configuration @@ -371,7 +350,8 @@ static class TestingLegacyVelocityConfiguration extends MybatisLanguageDriverAutoConfiguration.LegacyVelocityConfiguration { } - private static class MyLanguageDriverConfig { + @org.springframework.context.annotation.Configuration + static class MyLanguageDriverConfig { @Bean FreeMarkerLanguageDriver myFreeMarkerLanguageDriver() { return new FreeMarkerLanguageDriver(); @@ -388,14 +368,16 @@ ThymeleafLanguageDriver myThymeleafLanguageDriver() { } } - private static class ThymeleafCustomLanguageDriverConfig { + @org.springframework.context.annotation.Configuration + static class ThymeleafCustomLanguageDriverConfig { @Bean ThymeleafLanguageDriverConfig thymeleafLanguageDriverConfig() { return ThymeleafLanguageDriverConfig.newInstance(c -> c.getDialect().setPrefix("m")); } } - private static class FreeMarkerCustomLanguageDriverConfig { + @org.springframework.context.annotation.Configuration + static class FreeMarkerCustomLanguageDriverConfig { @Bean FreeMarkerLanguageDriverConfig freeMarkerLanguageDriverConfig() { return FreeMarkerLanguageDriverConfig @@ -403,7 +385,8 @@ FreeMarkerLanguageDriverConfig freeMarkerLanguageDriverConfig() { } } - private static class VelocityCustomLanguageDriverConfig { + @org.springframework.context.annotation.Configuration + static class VelocityCustomLanguageDriverConfig { @Bean VelocityLanguageDriverConfig velocityLanguageDriverConfig() { return VelocityLanguageDriverConfig.newInstance( diff --git a/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/TestAutoConfigurationPackage.java b/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/TestAutoConfigurationPackage.java new file mode 100644 index 000000000..cfd77bddb --- /dev/null +++ b/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/TestAutoConfigurationPackage.java @@ -0,0 +1,36 @@ +/* + * Copyright 2015-2022 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.mybatis.spring.boot.autoconfigure; + +import java.lang.annotation.*; + +import org.springframework.boot.autoconfigure.AutoConfigurationPackages; +import org.springframework.context.annotation.Import; + +/** + * Test annotation to configure the {@link AutoConfigurationPackages} to an arbitrary value. + * + * @author Phillip Webb + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Import(TestAutoConfigurationPackageRegistrar.class) +public @interface TestAutoConfigurationPackage { + + Class value(); + +} diff --git a/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java b/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java new file mode 100644 index 000000000..3f6288601 --- /dev/null +++ b/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java @@ -0,0 +1,39 @@ +/* + * Copyright 2015-2022 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.mybatis.spring.boot.autoconfigure; + +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.boot.autoconfigure.AutoConfigurationPackages; +import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; +import org.springframework.core.annotation.AnnotationAttributes; +import org.springframework.core.type.AnnotationMetadata; +import org.springframework.util.ClassUtils; + +/** + * {@link ImportBeanDefinitionRegistrar} to store the base package for tests. + * + * @author Phillip Webb + */ +public class TestAutoConfigurationPackageRegistrar implements ImportBeanDefinitionRegistrar { + + @Override + public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { + AnnotationAttributes attributes = AnnotationAttributes + .fromMap(metadata.getAnnotationAttributes(TestAutoConfigurationPackage.class.getName(), true)); + AutoConfigurationPackages.register(registry, ClassUtils.getPackageName(attributes.getString("value"))); + } + +} From 132326047590dd1d5e2300852b1cb39c94689e51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edd=C3=BA=20Mel=C3=A9ndez?= Date: Sun, 15 May 2022 11:04:43 -0500 Subject: [PATCH 3/4] Fix tests --- ...isLanguageDriverAutoConfigurationTest.java | 115 +++++++++--------- 1 file changed, 60 insertions(+), 55 deletions(-) diff --git a/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/MybatisLanguageDriverAutoConfigurationTest.java b/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/MybatisLanguageDriverAutoConfigurationTest.java index e5780af4f..40e2f215b 100644 --- a/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/MybatisLanguageDriverAutoConfigurationTest.java +++ b/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/MybatisLanguageDriverAutoConfigurationTest.java @@ -34,15 +34,19 @@ import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.directive.Directive; import org.apache.velocity.runtime.parser.node.Node; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mybatis.scripting.freemarker.FreeMarkerLanguageDriver; import org.mybatis.scripting.freemarker.FreeMarkerLanguageDriverConfig; import org.mybatis.scripting.thymeleaf.TemplateEngineCustomizer; import org.mybatis.scripting.thymeleaf.ThymeleafLanguageDriver; import org.mybatis.scripting.thymeleaf.ThymeleafLanguageDriverConfig; +import org.mybatis.scripting.velocity.VelocityFacade; import org.mybatis.scripting.velocity.VelocityLanguageDriver; import org.mybatis.scripting.velocity.VelocityLanguageDriverConfig; import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.thymeleaf.TemplateEngine; @@ -58,6 +62,12 @@ class MybatisLanguageDriverAutoConfigurationTest { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MybatisLanguageDriverAutoConfiguration.class)); + @BeforeEach + @AfterEach + void initializeVelocity() { + VelocityFacade.destroy(); + } + @Test void testDefaultConfiguration() { this.contextRunner.run(context -> { @@ -104,12 +114,11 @@ void testDefaultConfiguration() { @Test void testCustomConfiguration() { - this.contextRunner.withUserConfiguration(MyLanguageDriverConfig.class) - .run(context -> { - Map languageDriverBeans = context.getBeansOfType(LanguageDriver.class); - assertThat(languageDriverBeans).hasSize(3).containsKeys("myFreeMarkerLanguageDriver", - "myVelocityLanguageDriver", "myThymeleafLanguageDriver"); - }); + this.contextRunner.withUserConfiguration(MyLanguageDriverConfig.class).run(context -> { + Map languageDriverBeans = context.getBeansOfType(LanguageDriver.class); + assertThat(languageDriverBeans).hasSize(3).containsKeys("myFreeMarkerLanguageDriver", "myVelocityLanguageDriver", + "myThymeleafLanguageDriver"); + }); } @Test @@ -129,58 +138,54 @@ void testLegacyConfiguration() { @Test void testCustomThymeleafConfig() { - this.contextRunner - .withUserConfiguration(ThymeleafCustomLanguageDriverConfig.class) - .run(context -> { - ThymeleafLanguageDriver driver = context.getBean(ThymeleafLanguageDriver.class); - SqlSource sqlSource = driver.createSqlSource(new Configuration(), - "SELECT * FROM users WHERE id = /*[# m:p='id']*/ 1 /*[/]*/", Integer.class); - BoundSql boundSql = sqlSource.getBoundSql(10); - assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ?"); - assertThat(boundSql.getParameterObject()).isEqualTo(10); - assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id"); - assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class); - ThymeleafLanguageDriverConfig config = context.getBean(ThymeleafLanguageDriverConfig.class); - assertThat(config.isUse2way()).isTrue(); - assertThat(config.getDialect().getPrefix()).isEqualTo("m"); - assertThat(config.getDialect().getLikeAdditionalEscapeTargetChars()).isNull(); - assertThat(config.getDialect().getLikeEscapeChar()).isEqualTo('\\'); - assertThat(config.getDialect().getLikeEscapeClauseFormat()).isEqualTo("ESCAPE '%s'"); - assertThat(config.getTemplateFile().getBaseDir()).isEmpty(); - assertThat(config.getTemplateFile().getCacheTtl()).isNull(); - assertThat(config.getTemplateFile().getEncoding()).isEqualTo(StandardCharsets.UTF_8); - assertThat(config.getTemplateFile().getPatterns()).hasSize(1).contains("*.sql"); - assertThat(config.getCustomizer()).isNull(); - }); + this.contextRunner.withUserConfiguration(ThymeleafCustomLanguageDriverConfig.class).run(context -> { + ThymeleafLanguageDriver driver = context.getBean(ThymeleafLanguageDriver.class); + SqlSource sqlSource = driver.createSqlSource(new Configuration(), + "SELECT * FROM users WHERE id = /*[# m:p='id']*/ 1 /*[/]*/", Integer.class); + BoundSql boundSql = sqlSource.getBoundSql(10); + assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ?"); + assertThat(boundSql.getParameterObject()).isEqualTo(10); + assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id"); + assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class); + ThymeleafLanguageDriverConfig config = context.getBean(ThymeleafLanguageDriverConfig.class); + assertThat(config.isUse2way()).isTrue(); + assertThat(config.getDialect().getPrefix()).isEqualTo("m"); + assertThat(config.getDialect().getLikeAdditionalEscapeTargetChars()).isNull(); + assertThat(config.getDialect().getLikeEscapeChar()).isEqualTo('\\'); + assertThat(config.getDialect().getLikeEscapeClauseFormat()).isEqualTo("ESCAPE '%s'"); + assertThat(config.getTemplateFile().getBaseDir()).isEmpty(); + assertThat(config.getTemplateFile().getCacheTtl()).isNull(); + assertThat(config.getTemplateFile().getEncoding()).isEqualTo(StandardCharsets.UTF_8); + assertThat(config.getTemplateFile().getPatterns()).hasSize(1).contains("*.sql"); + assertThat(config.getCustomizer()).isNull(); + }); } @Test void testCustomFreeMarkerConfig() { - this.contextRunner - .withUserConfiguration(FreeMarkerCustomLanguageDriverConfig.class) - .run(context -> { - FreeMarkerLanguageDriver driver = context.getBean(FreeMarkerLanguageDriver.class); - @SuppressWarnings("unused") - class Param { - private Integer id; - private Integer version; - } - Param params = new Param(); - params.id = 10; - params.version = 20; - SqlSource sqlSource = driver.createSqlSource(new Configuration(), - "SELECT * FROM users WHERE id = #{id} and version = <@p name='version'/>", Param.class); - BoundSql boundSql = sqlSource.getBoundSql(params); - assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ? and version = ?"); - assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id"); - assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class); - assertThat(boundSql.getParameterMappings().get(1).getProperty()).isEqualTo("version"); - assertThat(boundSql.getParameterMappings().get(1).getJavaType()).isEqualTo(Integer.class); - FreeMarkerLanguageDriverConfig config = context.getBean(FreeMarkerLanguageDriverConfig.class); - assertThat(config.getBasePackage()).isEmpty(); - assertThat(config.getFreemarkerSettings()).hasSize(1); - assertThat(config.getFreemarkerSettings()).containsEntry("interpolation_syntax", "dollar"); - }); + this.contextRunner.withUserConfiguration(FreeMarkerCustomLanguageDriverConfig.class).run(context -> { + FreeMarkerLanguageDriver driver = context.getBean(FreeMarkerLanguageDriver.class); + @SuppressWarnings("unused") + class Param { + private Integer id; + private Integer version; + } + Param params = new Param(); + params.id = 10; + params.version = 20; + SqlSource sqlSource = driver.createSqlSource(new Configuration(), + "SELECT * FROM users WHERE id = #{id} and version = <@p name='version'/>", Param.class); + BoundSql boundSql = sqlSource.getBoundSql(params); + assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ? and version = ?"); + assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id"); + assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class); + assertThat(boundSql.getParameterMappings().get(1).getProperty()).isEqualTo("version"); + assertThat(boundSql.getParameterMappings().get(1).getJavaType()).isEqualTo(Integer.class); + FreeMarkerLanguageDriverConfig config = context.getBean(FreeMarkerLanguageDriverConfig.class); + assertThat(config.getBasePackage()).isEmpty(); + assertThat(config.getFreemarkerSettings()).hasSize(1); + assertThat(config.getFreemarkerSettings()).containsEntry("interpolation_syntax", "dollar"); + }); } @Test @@ -336,7 +341,7 @@ void testExcludeMybatisLanguageDriverAutoConfiguration() { .run(context -> assertThat(context.getBeanNamesForType(LanguageDriver.class)).isEmpty()); } - @org.springframework.context.annotation.Configuration + @EnableConfigurationProperties static class MyAutoConfiguration { } From f6502c53bba1c4864ed51655e7ce7f0d2d855de5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edd=C3=BA=20Mel=C3=A9ndez?= Date: Sat, 28 May 2022 20:47:50 -0500 Subject: [PATCH 4/4] Fix comments --- .../MybatisDependsOnDatabaseInitializationDetector.java | 1 + .../boot/autoconfigure/TestAutoConfigurationPackage.java | 8 ++++++-- .../TestAutoConfigurationPackageRegistrar.java | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/MybatisDependsOnDatabaseInitializationDetector.java b/mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/MybatisDependsOnDatabaseInitializationDetector.java index fb89bca78..dcf50722a 100644 --- a/mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/MybatisDependsOnDatabaseInitializationDetector.java +++ b/mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/MybatisDependsOnDatabaseInitializationDetector.java @@ -26,6 +26,7 @@ * {@link DependsOnDatabaseInitializationDetector} for Mybatis. * * @author Eddú Meléndez + * @since 2.3.0 */ class MybatisDependsOnDatabaseInitializationDetector extends AbstractBeansOfTypeDependsOnDatabaseInitializationDetector { diff --git a/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/TestAutoConfigurationPackage.java b/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/TestAutoConfigurationPackage.java index cfd77bddb..919995432 100644 --- a/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/TestAutoConfigurationPackage.java +++ b/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/TestAutoConfigurationPackage.java @@ -15,7 +15,11 @@ */ package org.mybatis.spring.boot.autoconfigure; -import java.lang.annotation.*; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; +import java.lang.annotation.RetentionPolicy; import org.springframework.boot.autoconfigure.AutoConfigurationPackages; import org.springframework.context.annotation.Import; @@ -23,7 +27,7 @@ /** * Test annotation to configure the {@link AutoConfigurationPackages} to an arbitrary value. * - * @author Phillip Webb + * @author Eddú Meléndez */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) diff --git a/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java b/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java index 3f6288601..2eada8b88 100644 --- a/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java +++ b/mybatis-spring-boot-autoconfigure/src/test/java/org/mybatis/spring/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java @@ -25,7 +25,7 @@ /** * {@link ImportBeanDefinitionRegistrar} to store the base package for tests. * - * @author Phillip Webb + * @author Eddú Meléndez */ public class TestAutoConfigurationPackageRegistrar implements ImportBeanDefinitionRegistrar {