- Notifications
You must be signed in to change notification settings - Fork39
A library for creating isolated embedded databases for Spring-powered integration tests.
License
zonkyio/embedded-database-spring-test
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
The primary goal of this project is to make it easier to write Spring-powered integration tests that rely onPostgreSQL,MSSQL,MySQL orMariaDB databases. This library is responsible for creating and managing isolated embedded databases for each test class or test method, based on a test configuration.
- Supports both
SpringandSpring Bootframeworks- Spring
4.3.8-7.0.x - Spring Boot
1.4.6-4.0.x
- Spring
- Supports multiple different databases
- Supports multiple database providers
- Supports various database migration tools
- Flyway,Liquibase,Spring
@Sqlannotation and others
- Flyway,Liquibase,Spring
Although this library usesTestcontainers under the hood (unless you choose adifferent provider), it offers several significant advantages over usingTestcontainers directly, especially for larger projects with complex schemas and many database migrations. See a more detailed description of the benefits below.
You don't have to write any additional code, explore the internals of the Spring framework, deal with context caching and so on.Just add a maven dependency to your project and declare the@AutoConfigureEmbeddedDatabase annotation on a test class and that's all!You can check out thequick start section for more information.
The library can cache Flyway and Liquibase migrations in template databases, which means database migrations typically need to be executed only once,regardless of how many tests use the database. This dramatically reduces initialization time in projects with complex migration scripts.
Using template databases enables fast binary copying of database state. This allows therefresh modeto provide complete test isolation while keeping the refresh operation very fast (typically milliseconds), even for larger databases with committed changes.The refresh functionality effectively rolls back any changes made during tests.
Additional performance features includedatabase prefetching andbackground bootstrapping mode.
You don't need to use the@DirtiesContext annotation to get a fresh database anymore!Use@AutoConfigureEmbeddedDatabase(refresh = AFTER_CLASS) or@AutoConfigureEmbeddedDatabase(refresh = AFTER_EACH_TEST_METHOD) instead to achieve the ideal isolation of your tests.
The semantics of those annotations is very similar, but the difference in performance is noticeable.While the@DirtiesContext annotation forces a refresh of the entire Spring context, therefresh mode of the@AutoConfigureEmbeddedDatabase annotation only refreshes data source beans and updates their references in other components.Depending on the size of the context, the difference can be even several tens of seconds.
If you are upgrading from the1.x version, check therelease notes.You’ll findupgrade instructions along with a list ofnew and noteworthy features.
Add the following Maven dependency:
<dependency> <groupId>io.zonky.test</groupId> <artifactId>embedded-database-spring-test</artifactId> <version>2.7.1</version> <scope>test</scope></dependency>
Also, make sure your application contains a dependency with the database driver for one of thesupported databases.
The configuration of the embedded database is driven by the@AutoConfigureEmbeddedDatabase annotation. Just declare the annotation on a test class and that's it! The existing data source will be replaced with the testing one, or a new data source will be created.
A new data source will be created and injected into all related components. You can also inject it into a test class as shown below.
@RunWith(SpringRunner.class)@AutoConfigureEmbeddedDatabasepublicclassEmptyDatabaseIntegrationTest {@AutowiredprivateDataSourcedataSource;// class body...}
In case the test class uses a spring context that already contains a data source bean, the data source bean will be automatically replaced with a testing data source.The newly created data source bean will be injected into all related components, and you can also inject it into a test class.
@RunWith(SpringRunner.class)@AutoConfigureEmbeddedDatabase@ContextConfiguration("path/to/application-config.xml")publicclassEmptyDatabaseIntegrationTest {// class body...}
Please note that if the context contains multiple data sources, the bean name must be specified using@AutoConfigureEmbeddedDatabase(beanName = "dataSource") to identify the data source that will be replaced.
The@AutoConfigureEmbeddedDatabase is a repeatable annotation, so you can annotate a test class with multiple annotations to create multiple independent databases.Each of them may have completely different configuration parameters, including the database provider as demonstrated in the example below.
@RunWith(SpringRunner.class)@AutoConfigureEmbeddedDatabase(beanName ="dataSource1")@AutoConfigureEmbeddedDatabase(beanName ="dataSource2",provider =ZONKY)@AutoConfigureEmbeddedDatabase(beanName ="dataSource3",provider =YANDEX)publicclassMultipleDatabasesIntegrationTest {@AutowiredprivateDataSourcedataSource1;@AutowiredprivateDataSourcedataSource2;@AutowiredprivateDataSourcedataSource3;// class body...}
Note that if multiple annotations on a single class are applied, some optimization techniques cannot be used and database initialization or refresh may be slower.
The refresh mode allows you to reset the database to the initial state that existed before the test was started.You can choose whether the database will be refreshed only between test classes or for each test method,and whether the refresh should take place before or after the test execution.
Please note that by default, if you do not specify the refresh mode explicitly, all tests in the project share the same database.
@RunWith(SpringRunner.class)@AutoConfigureEmbeddedDatabase(refresh =AFTER_EACH_TEST_METHOD)publicclassEmptyDatabaseIntegrationTest {@TestpublicvoidtestMethod1() {// fresh database }@TestpublicvoidtestMethod2() {// fresh database }}
This feature uses template databases internally and does not rely on the rollback of the current transaction or cleaning the database.Therefore, the refresh operation can be relatively fast and efficient, and even the data that has been committed will be reverted.If database prefetching is used and tuned properly, the refresh operation can only take a few milliseconds even for large databases.
Note that the refresh mode can be combined with@FlywayTest, Spring@Sql or Spring Boot's annotations without any negative impact on performance.
Spring Boot provides several annotations to simplify writing integration tests.One of them is the@DataJpaTest annotation, which can be used when a test focuses only on JPA components.By default, the tests annotated with this annotation use an in-memory database.But if the@DataJpaTest annotation is used together with the@AutoConfigureEmbeddedDatabase annotation,the in-memory database is automatically disabled and replaced with an embedded database.
@RunWith(SpringRunner.class)@DataJpaTest@AutoConfigureEmbeddedDatabasepublicclassSpringDataJpaAnnotationTest {// class body...}
You can also consider creating a customcomposed annotation.
Example of composed annotation
@Documented@Inherited@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@DataJpaTest@AutoConfigureEmbeddedDatabase(type =POSTGRES)public @interfacePostgresDataJpaTest {@AliasFor(annotation =DataJpaTest.class)booleanshowSql()defaulttrue;@AliasFor(annotation =DataJpaTest.class)booleanuseDefaultFilters()defaulttrue;@AliasFor(annotation =DataJpaTest.class)Filter[]includeFilters()default {};@AliasFor(annotation =DataJpaTest.class)Filter[]excludeFilters()default {};@AliasFor(annotation =DataJpaTest.class)Class<?>[]excludeAutoConfiguration()default {};}
Spring provides the@Sql annotation that can be used to annotate a test class or test method to configure sql scripts to be run against an embedded database during tests.
@RunWith(SpringRunner.class)@Sql({"/test-schema.sql","/test-user-data.sql"})@AutoConfigureEmbeddedDatabasepublicclassSpringSqlAnnotationTest {// class body...}
Note that the@Sql annotation can be combined with therefresh mode.
The library supports the use of@FlywayTest annotation. If you use it, the embedded database will be automatically initialized or cleaned by Flyway. If you don't specify any custom migration locations, the default pathdb/migration will be applied.
Please note that if you declare the annotation on a class, all tests within the class share the same database. If you want all the tests to be isolated, you have to declare the@FlywayTest annotation on each test method separately.Alternatively, you can also use therefresh mode.
@RunWith(SpringRunner.class)@FlywayTest// performs clean and migrate operations, with the same effect as the refresh mode@AutoConfigureEmbeddedDatabase@ContextConfiguration("path/to/application-config.xml")publicclassFlywayMigrationIntegrationTest {// class body...}
SeeUsage of FlywayTest Annotation for more information about configuration options of the@FlywayTest annotation.
Before you use PostgreSQL database, you have to add the following Maven dependency:
<dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.7.8</version></dependency>
Note that the associated database providers support all available featuressuch as template databases and database prefetching, which provides maximum performance.
Before you use Microsoft SQL Server, you have to add the following Maven dependency:
<dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>mssql-jdbc</artifactId> <version>13.2.1.jre11</version></dependency>
In the next step, you will need to accept an EULA for using the docker image.See the instructions here:https://www.testcontainers.org/modules/databases/mssqlserver.
Note that the associated database provider supports all available featuressuch as template databases and database prefetching.But because Microsoft SQL Server supports only a single template database per database instance,the template databases are emulated using backup and restore operations.However, this should have a minimal impact on the resulting performance.
Before you use MySQL database, you have to add the following Maven dependency:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version></dependency>
Note that the associated database provider only supports basic featuresthat are required to work the embedded database properly.So you may notice some performance degradation compared to other database providers.It's because in MySQL, thedatabase keyword is only synonymous with theschema keyword,which makes it hard to implement database prefetching.Template databases are also not supported and cannot be easily emulated because MySQL does not support fast binary backups.
Before you use MariaDB database, you have to add the following Maven dependency:
<dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <version>3.5.6</version></dependency>
Note that the associated database provider only supports basic featuresthat are required to work the embedded database properly.So you may notice some performance degradation compared to other database providers.It's because in MariaDB, thedatabase keyword is only synonymous with theschema keyword,which makes it hard to implement database prefetching.Template databases are also not supported and cannot be easily emulated because MariaDB does not support fast binary backups.
This provider may be convenient if you have an application that supports multiple databasesand you want to reuse the tests using the@AutoConfigureEmbeddedDatabase annotation for all these databases, including the H2 database.In this case, you can override thezonky.test.database.provider property externally and change the used database provider for each run without changing the code.You can find more information about externalized configuration here:https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config
Before you use H2 database, you have to add the following Maven dependency:
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>2.4.240</version></dependency>
Note that the associated database provider supports database prefetching, but not template databases.So you may notice some performance degradation compared to other database providers in some cases.
This provider may be convenient if you have an application that supports multiple databasesand you want to reuse the tests using the@AutoConfigureEmbeddedDatabase annotation for all these databases, including the HSQLDB database.In this case, you can override thezonky.test.database.provider property externally and change the used database provider for each run without changing the code.You can find more information about externalized configuration here:https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config
Before you use HSQLDB database, you have to add the following Maven dependency:
<dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>2.7.4</version></dependency>
Note that the associated database provider supports database prefetching, but not template databases.So you may notice some performance degradation compared to other database providers in some cases.
This provider may be convenient if you have an application that supports multiple databasesand you want to reuse the tests using the@AutoConfigureEmbeddedDatabase annotation for all these databases, including the Apache Derby database.In this case, you can override thezonky.test.database.provider property externally and change the used database provider for each run without changing the code.You can find more information about externalized configuration here:https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config
Before you use Apache Derby database, you have to add the following Maven dependency:
<dependency> <groupId>org.apache.derby</groupId> <artifactId>derby</artifactId> <version>10.17.1.0</version></dependency>
Note that the associated database provider supports database prefetching, but not template databases.So you may notice some performance degradation compared to other database providers in some cases.
Note that although any migration tool is supported,Flyway and Liquibase provide the best performancebecause the embedded database includes extra optimizations for them.
Before you use Flyway, you have to add the following Maven dependency:
<dependency> <groupId>org.flywaydb</groupId> <artifactId>flyway-core</artifactId> <version>11.14.1</version></dependency>
Optionally, you may also add the dependency for Flyway test extensions, which allows you to use the@FlywayTest annotation.
<dependency> <groupId>org.flywaydb.flyway-test-extensions</groupId> <artifactId>flyway-spring-test</artifactId> <version>10.0.0</version> <scope>test</scope></dependency>
Note that the processing of the@FlywayTest annotation is internally optimized and, if possible,database prefetching and template databases are used to speed up the application of new migrations after cleaning the database.This operation is internally identical to the use of therefresh mode,which can be used to replace or can be combined with the@FlywayTest annotation without any negative impact on performance.
Before you use Liquibase, you have to add the following Maven dependency:
<dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> <version>5.0.1</version></dependency>
Given that Liquibase does not offer an analogy to the@FlywayTest annotation,you may consider using therefresh mode to refresh an embedded database during tests.
The library can be combined with different database providers.Each of them has its advantages and disadvantages summarized in the table below.
Docker provides the greatest flexibility, but it can be slightly slower than the native versions.However, changing the database provider is really easy, so you can try them all.
You can either configure a provider for each class separately via the@AutoConfigureEmbeddedDatabase(provider = ...) annotation,or using thezonky.test.database.provider configuration property globally.
| Docker | Zonky | OpenTable | Yandex | |
|---|---|---|---|---|
| Startup Time | Slightly slower | Fast | Fast | Slow, depends on platform |
| Performance | Slightly slower, depends on platform | Native | Native | Native |
| Supported Databases | PostgreSQL, MSSQL, MySQL, MariaDB | PostgreSQL | PostgreSQL | PostgreSQL |
| Supported Platforms | All supported by Docker | Mac OS, Windows, Linux, Alpine Linux | Mac OS, Windows, Linux | Mac OS, Windows, Linux |
| Supported Architectures | Based on image | amd64, i386, arm32v6, arm32v7, arm64v8, ppc64le | amd64 | amd64 |
| Configurable Database Version | Yes, at runtime | Yes, at compile time | No | Yes, at runtime |
| Alpine Linux Support | Yes | Yes | No | No |
| Extension Support | Yes | No | No | No |
| In-Memory Support | Yes | No | No | No |
The@AutoConfigureEmbeddedDatabase annotation can be used for the basic configuration, the advanced configuration requires properties or yaml files.
zonky.test.database.type=auto# The type of embedded database to be created when replacing the data source.zonky.test.database.provider=default# Provider to be used to create the underlying embedded database.zonky.test.database.refresh=never# Determines the refresh mode of the embedded database.zonky.test.database.replace=any# Determines what type of existing DataSource beans can be replaced.zonky.test.database.init.script-locations=# Locations of the SQL scripts to apply to the database.zonky.test.database.init.continue-on-error=false# Whether initialization should continue when an error occurs.zonky.test.database.init.separator=; # Statement separator in the SQL scripts.zonky.test.database.init.encoding=# Encoding of the SQL scripts.zonky.test.database.postgres.client.properties.*=# Additional PostgreSQL options used to configure the test data source.zonky.test.database.mssql.client.properties.*=# Additional MSSQL options used to configure the test data source.zonky.test.database.mysql.client.properties.*=# Additional MySQL options used to configure the test data source.zonky.test.database.mariadb.client.properties.*=# Additional MariaDB options used to configure the test data source.
Note that the library includesconfiguration metadata that offer contextual help and code completion as users are working with Spring Boot'sapplication.properties orapplication.yml files.
The following configuration keys are honored by all postgres providers:
zonky.test.database.postgres.initdb.properties.*=# Additional PostgreSQL options to pass to initdb command during the database initialization.zonky.test.database.postgres.server.properties.*=# Additional PostgreSQL options used to configure the embedded database server.
Example configuration:
zonky.test.database.postgres.client.properties.stringtype=unspecifiedzonky.test.database.postgres.initdb.properties.lc-collate=cs_CZ.UTF-8zonky.test.database.postgres.initdb.properties.lc-monetary=cs_CZ.UTF-8zonky.test.database.postgres.initdb.properties.lc-numeric=cs_CZ.UTF-8zonky.test.database.postgres.server.properties.shared_buffers=512MBzonky.test.database.postgres.server.properties.max_connections=100
This is the default provider, so you do not have to do anything special,just use the@AutoConfigureEmbeddedDatabase annotation in its basic form without specifying any provider.
@RunWith(SpringRunner.class)@AutoConfigureEmbeddedDatabasepublicclassDefaultProviderIntegrationTest {// class body...}
Note that the Docker provider is especially useful if you need to use some database extensions,or if you want to prepare a custom docker image containing some test data.In such cases, you can use any docker image compatible with the official docker images of the supported databases.
The provider configuration can be managed via properties in thezonky.test.database.postgres.docker,zonky.test.database.mysql.docker,zonky.test.database.mariadb.dockerandzonky.test.database.mssql.docker groups as shown below.
zonky.test.database.postgres.docker.image=postgres:11-alpine# Docker image containing PostgreSQL database.zonky.test.database.postgres.docker.tmpfs.enabled=false# Whether to mount postgres data directory as tmpfs.zonky.test.database.postgres.docker.tmpfs.options=rw,noexec,nosuid# Mount options used to configure the tmpfs filesystem.zonky.test.database.mysql.docker.image=mysql:5.7# Docker image containing MySQL database.zonky.test.database.mysql.docker.tmpfs.enabled=false# Whether to mount database data directory as tmpfs.zonky.test.database.mysql.docker.tmpfs.options=rw,noexec,nosuid# Mount options used to configure the tmpfs filesystem.zonky.test.database.mariadb.docker.image=mariadb:10.4# Docker image containing MariaDB database.zonky.test.database.mariadb.docker.tmpfs.enabled=false# Whether to mount database data directory as tmpfs.zonky.test.database.mariadb.docker.tmpfs.options=rw,noexec,nosuid# Mount options used to configure the tmpfs filesystem.zonky.test.database.mssql.docker.image=mcr.microsoft.com/mssql/server:2017-latest# Docker image containing MSSQL database.
Or, the provider configuration can also be customized with a bean implementingPostgreSQLContainerCustomizer interface.
importio.zonky.test.db.config.PostgreSQLContainerCustomizer;@ConfigurationpublicclassEmbeddedPostgresConfiguration {@BeanpublicPostgreSQLContainerCustomizerpostgresContainerCustomizer() {returncontainer ->container.withStartupTimeout(Duration.ofSeconds(60L)); }}
@RunWith(SpringRunner.class)@AutoConfigureEmbeddedDatabase@ContextConfiguration(classes =EmbeddedPostgresConfiguration.class)publicclassEmbeddedPostgresIntegrationTest {// class body...}
Before you use the Zonky provider, you have to add the following Maven dependency:
<dependency> <groupId>io.zonky.test</groupId> <artifactId>embedded-postgres</artifactId> <version>2.2.0</version> <scope>test</scope></dependency>
Then, you can use the@AutoConfigureEmbeddedDatabase annotation to set up theDatabaseProvider.ZONKY provider.
@RunWith(SpringRunner.class)@AutoConfigureEmbeddedDatabase(provider =ZONKY)publicclassZonkyProviderIntegrationTest {// class body...}
Note that the Zonky provider can be useful as an alternative if you can't use Docker for some reason,and in version1.x.x it used to be the default provider.
The version of the binaries is configurable at compile time by importingembedded-postgres-binaries-bom in a required version into your dependency management section.
<dependencyManagement> <dependencies> <dependency> <groupId>io.zonky.test.postgres</groupId> <artifactId>embedded-postgres-binaries-bom</artifactId> <version>18.1.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies></dependencyManagement>
Find more information about this topic here:https://github.com/zonkyio/embedded-postgres#postgres-version
By default, only the support foramd64 architecture is enabled.Support for other architectures can be enabled using the following instructions:https://github.com/zonkyio/embedded-postgres#additional-architectures
The provider configuration can be customized with a bean implementingConsumer<EmbeddedPostgres.Builder> interface.The obtained builder provides methods to change the configuration before the database is started.
importio.zonky.test.db.postgres.embedded.EmbeddedPostgres;@ConfigurationpublicclassEmbeddedPostgresConfiguration {@BeanpublicConsumer<EmbeddedPostgres.Builder>embeddedPostgresCustomizer() {returnbuilder ->builder.setPGStartupWait(Duration.ofSeconds(60L)); }}
@RunWith(SpringRunner.class)@AutoConfigureEmbeddedDatabase(provider =ZONKY)@ContextConfiguration(classes =EmbeddedPostgresConfiguration.class)publicclassEmbeddedPostgresIntegrationTest {// class body...}
Before you use the OpenTable provider, you have to add the following Maven dependency:
<dependency> <groupId>com.opentable.components</groupId> <artifactId>otj-pg-embedded</artifactId> <version>0.13.1</version> <scope>test</scope></dependency>
Then, you can use the@AutoConfigureEmbeddedDatabase annotation to set up theDatabaseProvider.OPENTABLE provider.
@RunWith(SpringRunner.class)@AutoConfigureEmbeddedDatabase(provider =OPENTABLE)publicclassOpenTableProviderIntegrationTest {// class body...}
The provider configuration can be customized with a bean implementingConsumer<EmbeddedPostgres.Builder> interface.The obtained builder provides methods to change the configuration before the database is being started.
importcom.opentable.db.postgres.embedded.EmbeddedPostgres;@ConfigurationpublicclassEmbeddedPostgresConfiguration {@BeanpublicConsumer<EmbeddedPostgres.Builder>embeddedPostgresCustomizer() {returnbuilder ->builder.setPGStartupWait(Duration.ofSeconds(60L)); }}
@RunWith(SpringRunner.class)@AutoConfigureEmbeddedDatabase(provider =OPENTABLE)@ContextConfiguration(classes =EmbeddedPostgresConfiguration.class)publicclassEmbeddedPostgresIntegrationTest {// class body...}
Before you use the Yandex provider, you have to add the following Maven dependency:
<dependency> <groupId>ru.yandex.qatools.embed</groupId> <artifactId>postgresql-embedded</artifactId> <version>2.10</version> <scope>test</scope></dependency>
Then, you can use the@AutoConfigureEmbeddedDatabase annotation to set up theDatabaseProvider.YANDEX provider.
@RunWith(SpringRunner.class)@AutoConfigureEmbeddedDatabase(provider =YANDEX)publicclassYandexProviderIntegrationTest {// class body...}
The provider configuration can be managed via properties in thezonky.test.database.postgres.yandex-provider group.
zonky.test.database.postgres.yandex-provider.postgres-version=11.10-1# Version of EnterpriseDB PostgreSQL binaries (https://www.enterprisedb.com/download-postgresql-binaries).
The database prefetching feature is used to speed up the initialization of new databases by loading the databases in advance and maintaining them in an internal buffer to make them available as fast as possible. The prefetching can be customized by properties in thezonky.test.database.prefetching group.
zonky.test.database.prefetching.thread-name-prefix=prefetching-# Prefix to use for the names of database prefetching threads.zonky.test.database.prefetching.concurrency=3# Maximum number of concurrently running database prefetching threads.zonky.test.database.prefetching.pipeline-cache-size=5# Maximum number of prepared databases per pipeline.zonky.test.database.prefetching.max-prepared-templates=10# Maximum number of prepared database templates.
By default, the library automatically registers all necessary context customizers and test execution listeners.If this behavior is inappropriate for some reason, you can deactivate it by excluding theembedded-database-spring-test-autoconfigure dependency.
<dependency> <groupId>io.zonky.test</groupId> <artifactId>embedded-database-spring-test</artifactId> <version>2.7.1</version> <scope>test</scope> <exclusions> <exclusion> <groupId>io.zonky.test</groupId> <artifactId>embedded-database-spring-test-autoconfigure</artifactId> </exclusion> </exclusions></dependency>
This feature is enabled out of the box and causes that the initialization of the data source and the execution of Flyway or Liquibase migrations are performed in background bootstrap mode.In such case, aDataSource proxy is immediately returned for injection purposes instead of waiting for the bootstrapping to complete.However, note that the first actual call to a data source method will then block until the bootstrapping is completed, if not ready by then.For maximum benefit, make sure to avoid early data source calls in init methods of related beans.
When you use a breakpoint to pause the test, you can connect to the temporary embedded database. Connection details can be found in the log as shown in the example below:
i.z.t.d.l.EmbeddedDatabaseReporter - JDBC URL to connect to 'dataSource1': url='jdbc:postgresql://localhost:55112/fynwkrpzfcyj?user=postgres', scope='TestClass#testMethod'TIP: You can use the followingIntelliJ IDEA plugin to automatically synchronize the database settings according to the connection strings in the log produced by the library:https://gist.github.com/tomix26/9e1ea63353707ef3b5cf4869fc50eec2
Note that if you are using therefresh mode or the@FlywayTest annotation, there may be several similar records in the log but always with a different scope. That's because in this case multiple isolated databases may be created.
Check the console output for theinitdb: cannot be run as root message. If the error is present, try to upgrade to a newer version of the library (1.5.5+), or ensure the build process is running as a non-root user.
If the error is not present, try to clean up the/tmp/embedded-pg/PG-XYZ directory containing temporary binaries of the embedded database.
You probably need to installMicrosoft Visual C++ 2013 Redistributable Package. The 2013 version is important, installing other versions does not help. The problem is discussed in more detailhere.
Running builds inside a Docker container is fully supported, including Alpine Linux. However, PostgreSQL is restricted in that the database process must run under a non-root user. Otherwise, the database does not start and fails with an error.
So be sure to use a docker image that runs with a non-root user. Or, since version1.5.5 you can run the docker container with the--privileged option, which allows to take advantage of theunshare command to run the database process in a separate namespace.
Below are some examples of how to prepare a docker image running with a non-root user:
Standard Dockerfile
FROM openjdk:8-jdkRUN groupadd --system --gid 1000 testRUN useradd --system --gid test --uid 1000 --shell /bin/bash --create-home testUSER testWORKDIR /home/test
Alpine Dockerfile
FROM openjdk:8-jdk-alpineRUN addgroup -S -g 1000 testRUN adduser -D -S -G test -u 1000 -s /bin/ash testUSER testWORKDIR /home/test
Gitlab runner Docker executor
Configure the Docker container to run in privileged mode as describedhere.
[[runners]] executor = "docker" [runners.docker] privileged = trueThis combination is supported, however, additional configuration is required.You have to add the-v /var/run/docker.sock:/var/run/docker.sock mapping to the Docker command to map the Docker socket.Detailed instructions can be foundhere.
Make sure you do not useorg.flywaydb.test.junit.FlywayTestExecutionListener ororg.flywaydb.test.FlywayTestExecutionListener listeners. Because this library has its own test execution listener that can optimize database initialization.But this optimization has no effect if any of these listeners is also applied.
The project uses aGradle-based build system. In the instructionsbelow,./gradlew is invoked from the root of the source tree and serves asa cross-platform, self-contained bootstrap mechanism for the build.
Be sure that yourJAVA_HOME environment variable points to thejdk1.8.0 folderextracted from the JDK download.
git clone git@github.com:zonkyio/embedded-database-spring-test.git
./gradlew build
- Spring Framework (5.3.39) -
spring-test,spring-contextmodules - Testcontainers (1.18.3)
- Cedarsoftware (1.68.0)
- Guava (32.1.3-jre)
The project is released under version 2.0 of theApache License.
About
A library for creating isolated embedded databases for Spring-powered integration tests.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
