{"id":14969054,"url":"https://github.com/zonkyio/embedded-database-spring-test","last_synced_at":"2025-05-15T08:08:58.866Z","repository":{"id":28105885,"uuid":"114404733","full_name":"zonkyio/embedded-database-spring-test","owner":"zonkyio","description":"A library for creating isolated embedded databases for Spring-powered integration tests.","archived":false,"fork":false,"pushed_at":"2024-11-30T11:52:08.000Z","size":998,"stargazers_count":423,"open_issues_count":18,"forks_count":38,"subscribers_count":11,"default_branch":"master","last_synced_at":"2025-04-14T12:18:51.603Z","etag":null,"topics":["embedded-database","embedded-postgresql","flyway","h2-database","liquibase","mariadb","mssql","mysql","postgres","postgresql","spring-boot","spring-framework","spring-test","testcontainers"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zonkyio.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-12-15T19:29:33.000Z","updated_at":"2025-04-04T13:12:11.000Z","dependencies_parsed_at":"2024-01-17T02:01:19.618Z","dependency_job_id":"119d4599-c531-43cc-a969-69173142e183","html_url":"https://github.com/zonkyio/embedded-database-spring-test","commit_stats":{"total_commits":256,"total_committers":9,"mean_commits":"28.444444444444443","dds":0.390625,"last_synced_commit":"49e474f4bcaae7ae7e831e9d5e3646465a46a5c8"},"previous_names":[],"tags_count":32,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zonkyio%2Fembedded-database-spring-test","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zonkyio%2Fembedded-database-spring-test/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zonkyio%2Fembedded-database-spring-test/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zonkyio%2Fembedded-database-spring-test/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zonkyio","download_url":"https://codeload.github.com/zonkyio/embedded-database-spring-test/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248877968,"owners_count":21176244,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["embedded-database","embedded-postgresql","flyway","h2-database","liquibase","mariadb","mssql","mysql","postgres","postgresql","spring-boot","spring-framework","spring-test","testcontainers"],"created_at":"2024-09-24T13:41:03.532Z","updated_at":"2025-04-14T12:18:57.264Z","avatar_url":"https://github.com/zonkyio.png","language":"Java","readme":"# \u003cimg src=\"zonky.jpg\" height=\"100\"\u003e Embedded Database\n\n## Introduction\n\nThe primary goal of this project is to make it easier to write Spring-powered integration tests that rely on `PostgreSQL`, `MSSQL`, `MySQL` or `MariaDB` databases. This library is responsible for creating and managing isolated embedded databases for each test class or test method, based on a test configuration.\n\n## Supported Integrations\n\n* Supports both `Spring` and `Spring Boot` frameworks\n  * Spring `4.3.8` - `6.2.x`\n  * Spring Boot `1.4.6` - `3.4.x`\n* Supports multiple different databases\n  * [PostgreSQL](#postgresql), [MSSQL](#microsoft-sql-server), [MySQL](#mysql), [MariaDB](#mariadb), [H2](#h2), [HSQLDB](#hsqldb), [Derby](#derby)\n* Supports multiple database providers\n  * [Docker / Testcontainers](#using-docker-provider-default), [Zonky](#using-zonky-provider-previous-default), [OpenTable](#using-opentable-provider), [Yandex](#using-yandex-provider)\n* Supports various database migration tools\n  * [Flyway](#flyway), [Liquibase](#liquibase), [Spring `@Sql` annotation](#using-spring-sql-annotation) and others\n\n## Main Goals\n\nAlthough this library uses `Testcontainers` under the hood (unless you choose a [different provider](#database-providers)), it offers several significant advantages over using `Testcontainers` directly, especially for larger projects with complex schemas and many database migrations. See a more detailed description of the benefits below.\n\n### Easy Integration\n\nYou don't have to write any additional code, explore the internals of the Spring framework, deal with context caching and so on.\nJust add a maven dependency to your project and declare the `@AutoConfigureEmbeddedDatabase` annotation on a test class and that's all!\nYou can check out the [quick start](#quick-start) section for more information.\n\n### Migration Caching\n\nThe library can cache Flyway and Liquibase migrations in template databases, which means database migrations typically need to be executed only once,\nregardless of how many tests use the database. This dramatically reduces initialization time in projects with complex migration scripts.\n\n### Efficient Database Isolation\n\nUsing template databases enables fast binary copying of database state. This allows the [refresh mode](#refreshing-the-database-during-tests)\nto provide complete test isolation while keeping the refresh operation very fast (typically milliseconds), even for larger databases with committed changes.\nThe refresh functionality effectively rolls back any changes made during tests.\n\nAdditional performance features include [database prefetching](#database-prefetching) and [background bootstrapping mode](#background-bootstrapping-mode).\n\n### Context Caching\n\nYou don't need to use the `@DirtiesContext` annotation to get a fresh database anymore!\nUse `@AutoConfigureEmbeddedDatabase(refresh = AFTER_CLASS)` or `@AutoConfigureEmbeddedDatabase(refresh = AFTER_EACH_TEST_METHOD)` instead to achieve the ideal isolation of your tests.\n\nThe semantics of those annotations is very similar, but the difference in performance is noticeable.\nWhile the `@DirtiesContext` annotation forces a refresh of the entire Spring context, the [refresh mode](#refreshing-the-database-during-tests) of the `@AutoConfigureEmbeddedDatabase` annotation only refreshes data source beans and updates their references in other components.\nDepending on the size of the context, the difference can be even several tens of seconds.\n\n## Upgrading from Embedded Database 1.x\n\nIf you are upgrading from the `1.x` version, check the [release notes](https://github.com/zonkyio/embedded-database-spring-test/wiki/Embedded-Database-2.0-Release-Notes).\nYou’ll find [upgrade instructions](https://github.com/zonkyio/embedded-database-spring-test/wiki/Embedded-Database-2.0-Release-Notes#upgrading-from-embedded-database-1x) along with a list of [new and noteworthy](https://github.com/zonkyio/embedded-database-spring-test/wiki/Embedded-Database-2.0-Release-Notes#new-and-noteworthy) features.\n\n## Quick Start\n\n### Maven Configuration\n\nAdd the following Maven dependency:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eio.zonky.test\u003c/groupId\u003e\n    \u003cartifactId\u003eembedded-database-spring-test\u003c/artifactId\u003e\n    \u003cversion\u003e2.6.0\u003c/version\u003e\n    \u003cscope\u003etest\u003c/scope\u003e\n\u003c/dependency\u003e\n```\n\nAlso, make sure your application contains a dependency with the database driver for one of the [supported databases](#supported-databases).\n\n### Basic Usage\n\nThe 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.\n\n## Examples\n\n### Creating a new empty database\n\nA new data source will be created and injected into all related components. You can also inject it into a test class as shown below. \n\n```java\n@RunWith(SpringRunner.class)\n@AutoConfigureEmbeddedDatabase\npublic class EmptyDatabaseIntegrationTest {\n    \n    @Autowired\n    private DataSource dataSource;\n    \n    // class body...\n}\n```\n\n### Replacing an existing data source with an empty database\n\nIn 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.\nThe newly created data source bean will be injected into all related components, and you can also inject it into a test class.\n\n```java\n@RunWith(SpringRunner.class)\n@AutoConfigureEmbeddedDatabase\n@ContextConfiguration(\"path/to/application-config.xml\")\npublic class EmptyDatabaseIntegrationTest {\n    // class body...\n}\n```\n\nPlease 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.\n\n### Creating multiple databases within a single test class\n\nThe `@AutoConfigureEmbeddedDatabase` is a repeatable annotation, so you can annotate a test class with multiple annotations to create multiple independent databases.\nEach of them may have completely different configuration parameters, including the database provider as demonstrated in the example below.\n\n```java\n@RunWith(SpringRunner.class)\n@AutoConfigureEmbeddedDatabase(beanName = \"dataSource1\")\n@AutoConfigureEmbeddedDatabase(beanName = \"dataSource2\", provider = ZONKY)\n@AutoConfigureEmbeddedDatabase(beanName = \"dataSource3\", provider = YANDEX)\npublic class MultipleDatabasesIntegrationTest {\n    \n    @Autowired\n    private DataSource dataSource1;\n    @Autowired\n    private DataSource dataSource2;\n    @Autowired\n    private DataSource dataSource3;\n    \n    // class body...\n}\n```\n\nNote that if multiple annotations on a single class are applied, some optimization techniques cannot be used and database initialization or refresh may be slower.\n\n### Refreshing the database during tests\n\nThe refresh mode allows you to reset the database to the initial state that existed before the test was started.\nYou can choose whether the database will be refreshed only between test classes or for each test method,\nand whether the refresh should take place before or after the test execution.\n\nPlease note that by default, if you do not specify the refresh mode explicitly, all tests in the project share the same database. \n\n```java\n@RunWith(SpringRunner.class)\n@AutoConfigureEmbeddedDatabase(refresh = AFTER_EACH_TEST_METHOD)\npublic class EmptyDatabaseIntegrationTest {\n\n        @Test\n        public void testMethod1() {\n            // fresh database\n        }\n\n        @Test\n        public void testMethod2() {\n            // fresh database\n        }\n}\n```\n\nThis feature uses template databases internally and does not rely on the rollback of the current transaction or cleaning the database.\nTherefore, the refresh operation can be relatively fast and efficient, and even the data that has been committed will be reverted.\nIf database prefetching is used and tuned properly, the refresh operation can only take a few milliseconds even for large databases.\n\nNote that the refresh mode can be combined with `@FlywayTest`, Spring `@Sql` or Spring Boot's annotations without any negative impact on performance.\n\n### Using `@DataJpaTest` or `@JdbcTest` annotation\n\nSpring Boot provides several annotations to simplify writing integration tests.\nOne of them is the `@DataJpaTest` annotation, which can be used when a test focuses only on JPA components.\nBy default, the tests annotated with this annotation use an in-memory database.\nBut if the `@DataJpaTest` annotation is used together with the `@AutoConfigureEmbeddedDatabase` annotation,\nthe in-memory database is automatically disabled and replaced with an embedded database. \n\n```java\n@RunWith(SpringRunner.class)\n@DataJpaTest\n@AutoConfigureEmbeddedDatabase\npublic class SpringDataJpaAnnotationTest {\n    // class body...\n}\n```\n\nYou can also consider creating a custom [composed annotation](https://github.com/spring-projects/spring-framework/wiki/Spring-Annotation-Programming-Model#composed-annotations).\n\n\u003cdetails\u003e\n  \u003csummary\u003eExample of composed annotation\u003c/summary\u003e\n  \n  ```java\n  @Documented\n  @Inherited\n  @Target(ElementType.TYPE)\n  @Retention(RetentionPolicy.RUNTIME)\n  @DataJpaTest\n  @AutoConfigureEmbeddedDatabase(type = POSTGRES)\n  public @interface PostgresDataJpaTest {\n  \n      @AliasFor(annotation = DataJpaTest.class)\n      boolean showSql() default true;\n  \n      @AliasFor(annotation = DataJpaTest.class)\n      boolean useDefaultFilters() default true;\n  \n      @AliasFor(annotation = DataJpaTest.class)\n      Filter[] includeFilters() default {};\n  \n      @AliasFor(annotation = DataJpaTest.class)\n      Filter[] excludeFilters() default {};\n  \n      @AliasFor(annotation = DataJpaTest.class)\n      Class\u003c?\u003e[] excludeAutoConfiguration() default {};\n  \n  }\n  ```\n\n\u003c/details\u003e\n\n### Using Spring `@Sql` annotation\n\nSpring 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.\n\n```java\n@RunWith(SpringRunner.class)\n@Sql({\"/test-schema.sql\", \"/test-user-data.sql\"})\n@AutoConfigureEmbeddedDatabase\npublic class SpringSqlAnnotationTest {\n    // class body...\n}\n```\n\nNote that the `@Sql` annotation can be combined with the [refresh mode](#refreshing-the-database-during-tests).\n\n### Using `@FlywayTest` annotation\n\nThe 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 path `db/migration` will be applied.\n\nPlease 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.\nAlternatively, you can also use the [refresh mode](#refreshing-the-database-during-tests).\n\n```java\n@RunWith(SpringRunner.class)\n@FlywayTest // performs clean and migrate operations, with the same effect as the refresh mode\n@AutoConfigureEmbeddedDatabase\n@ContextConfiguration(\"path/to/application-config.xml\")\npublic class FlywayMigrationIntegrationTest {\n    // class body...\n}\n```\n\nSee [Usage of FlywayTest Annotation](https://github.com/flyway/flyway-test-extensions/wiki/Usage-of-Annotation-FlywayTest) for more information about configuration options of the `@FlywayTest` annotation.\n\n## Supported Databases\n\n### PostgreSQL\n\nBefore you use PostgreSQL database, you have to add the following Maven dependency:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.postgresql\u003c/groupId\u003e\n    \u003cartifactId\u003epostgresql\u003c/artifactId\u003e\n    \u003cversion\u003e42.2.18\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\nNote that the associated database providers support all available features\nsuch as template databases and database prefetching, which provides maximum performance.\n\n### Microsoft SQL Server\n\nBefore you use Microsoft SQL Server, you have to add the following Maven dependency:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003ecom.microsoft.sqlserver\u003c/groupId\u003e\n    \u003cartifactId\u003emssql-jdbc\u003c/artifactId\u003e\n    \u003cversion\u003e8.4.1.jre8\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n**In the next step, you will need to accept an EULA for using the docker image.**\nSee the instructions here: https://www.testcontainers.org/modules/databases/mssqlserver.\n\nNote that the associated database provider supports all available features\nsuch as template databases and database prefetching.\nBut because Microsoft SQL Server supports only a single template database per database instance,\nthe template databases are emulated using backup and restore operations.\nHowever, this should have a minimal impact on the resulting performance.\n\n### MySQL\n\nBefore you use MySQL database, you have to add the following Maven dependency:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003emysql\u003c/groupId\u003e\n    \u003cartifactId\u003emysql-connector-java\u003c/artifactId\u003e\n    \u003cversion\u003e8.0.22\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n**Note that the associated database provider only supports basic features**\n**that are required to work the embedded database properly.**\n**So you may notice some performance degradation compared to other database providers.**\nIt's because in MySQL, the `database` keyword is only synonymous with the `schema` keyword,\nwhich makes it hard to implement database prefetching.\nTemplate databases are also not supported and cannot be easily emulated because MySQL does not support fast binary backups.\n\n### MariaDB\n\nBefore you use MariaDB database, you have to add the following Maven dependency:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.mariadb.jdbc\u003c/groupId\u003e\n    \u003cartifactId\u003emariadb-java-client\u003c/artifactId\u003e\n    \u003cversion\u003e2.7.0\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n**Note that the associated database provider only supports basic features**\n**that are required to work the embedded database properly.**\n**So you may notice some performance degradation compared to other database providers.**\nIt's because in MariaDB, the `database` keyword is only synonymous with the `schema` keyword,\nwhich makes it hard to implement database prefetching.\nTemplate databases are also not supported and cannot be easily emulated because MariaDB does not support fast binary backups.\n\n### H2\n\nThis provider may be convenient if you have an application that supports multiple databases\nand you want to reuse the tests using the `@AutoConfigureEmbeddedDatabase` annotation for all these databases, including the H2 database.\nIn this case, you can override the `zonky.test.database.provider` property externally and change the used database provider for each run without changing the code.\nYou can find more information about externalized configuration here: https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config\n\nBefore you use H2 database, you have to add the following Maven dependency:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003ecom.h2database\u003c/groupId\u003e\n    \u003cartifactId\u003eh2\u003c/artifactId\u003e\n    \u003cversion\u003e2.1.214\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n**Note that the associated database provider supports database prefetching, but not template databases.\nSo you may notice some performance degradation compared to other database providers in some cases.**\n\n### HSQLDB\n\nThis provider may be convenient if you have an application that supports multiple databases\nand you want to reuse the tests using the `@AutoConfigureEmbeddedDatabase` annotation for all these databases, including the HSQLDB database.\nIn this case, you can override the `zonky.test.database.provider` property externally and change the used database provider for each run without changing the code.\nYou can find more information about externalized configuration here: https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config\n\nBefore you use HSQLDB database, you have to add the following Maven dependency:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.hsqldb\u003c/groupId\u003e\n    \u003cartifactId\u003ehsqldb\u003c/artifactId\u003e\n    \u003cversion\u003e2.7.1\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n**Note that the associated database provider supports database prefetching, but not template databases.\nSo you may notice some performance degradation compared to other database providers in some cases.**\n\n### Derby\n\nThis provider may be convenient if you have an application that supports multiple databases\nand you want to reuse the tests using the `@AutoConfigureEmbeddedDatabase` annotation for all these databases, including the Apache Derby database.\nIn this case, you can override the `zonky.test.database.provider` property externally and change the used database provider for each run without changing the code.\nYou can find more information about externalized configuration here: https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config\n\nBefore you use Apache Derby database, you have to add the following Maven dependency:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.apache.derby\u003c/groupId\u003e\n    \u003cartifactId\u003ederby\u003c/artifactId\u003e\n    \u003cversion\u003e10.16.1.1\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n**Note that the associated database provider supports database prefetching, but not template databases.\nSo you may notice some performance degradation compared to other database providers in some cases.**\n\n## Supported Migration Tools\n\nNote that although any migration tool is supported,\nFlyway and Liquibase provide the best performance\nbecause the embedded database includes extra optimizations for them.\n\n### Flyway\n\nBefore you use Flyway, you have to add the following Maven dependency:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.flywaydb\u003c/groupId\u003e\n    \u003cartifactId\u003eflyway-core\u003c/artifactId\u003e\n    \u003cversion\u003e7.3.0\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\nOptionally, you may also add the dependency for Flyway test extensions, which allows you to use the `@FlywayTest` annotation.\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.flywaydb.flyway-test-extensions\u003c/groupId\u003e\n    \u003cartifactId\u003eflyway-spring-test\u003c/artifactId\u003e\n    \u003cversion\u003e7.0.0\u003c/version\u003e\n    \u003cscope\u003etest\u003c/scope\u003e\n\u003c/dependency\u003e\n```\n\nNote that the processing of the `@FlywayTest` annotation is internally optimized and, if possible,\ndatabase prefetching and template databases are used to speed up the application of new migrations after cleaning the database.\nThis operation is internally identical to the use of the [refresh mode](#refreshing-the-database-during-tests),\nwhich can be used to replace or can be combined with the `@FlywayTest` annotation without any negative impact on performance.\n\n### Liquibase\n\nBefore you use Liquibase, you have to add the following Maven dependency:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.liquibase\u003c/groupId\u003e\n    \u003cartifactId\u003eliquibase-core\u003c/artifactId\u003e\n    \u003cversion\u003e3.10.3\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\nGiven that Liquibase does not offer an analogy to the `@FlywayTest` annotation,\nyou may consider using the [refresh mode](#refreshing-the-database-during-tests) to refresh an embedded database during tests.\n\n## Database Providers\n\nThe library can be combined with different database providers.\nEach of them has its advantages and disadvantages summarized in the table below.\n\nDocker provides the greatest flexibility, but it can be slightly slower than the native versions.\nHowever, changing the database provider is really easy, so you can try them all.\n\nYou can either configure a provider for each class separately via the `@AutoConfigureEmbeddedDatabase(provider = ...)` annotation,\nor using the `zonky.test.database.provider` configuration property globally.\n\n|                                   |       [Docker][docker-provider]      |             [Zonky][zonky-provider]             | [OpenTable][opentable-provider] | [Yandex][yandex-provider] |\n|:---------------------------------:|:------------------------------------:|:-----------------------------------------------:|:-------------------------------:|:-------------------------:|\n|          **Startup Time**         |            Slightly slower           |                       Fast                      |               Fast              | Slow, depends on platform |\n|          **Performance**          | Slightly slower, depends on platform |                      Native                     |              Native             |           Native          |\n|      **Supported Databases**      |   PostgreSQL, MSSQL, MySQL, MariaDB  |                    PostgreSQL                   |            PostgreSQL           |         PostgreSQL        |\n|      **Supported Platforms**      |        All supported by Docker       |       Mac OS, Windows, Linux, Alpine Linux      |      Mac OS, Windows, Linux     |   Mac OS, Windows, Linux  |\n|    **Supported Architectures**    |            Based on image            | amd64, i386, arm32v6, arm32v7, arm64v8, ppc64le |              amd64              |           amd64           |\n| **Configurable Database Version** |            Yes, at runtime           |               Yes, at compile time              |                No               |      Yes, at runtime      |\n|      **Alpine Linux Support**     |                  Yes                 |                       Yes                       |                No               |             No            |\n|       **Extension Support**       |                  Yes                 |                        No                       |                No               |             No            |\n|       **In-Memory Support**       |                  Yes                 |                        No                       |                No               |             No            |\n\n[docker-provider]: https://www.testcontainers.org\n[zonky-provider]: https://github.com/zonkyio/embedded-postgres\n[opentable-provider]: https://github.com/opentable/otj-pg-embedded\n[yandex-provider]: https://github.com/yandex-qatools/postgresql-embedded\n\n### Common Configuration\n\nThe `@AutoConfigureEmbeddedDatabase` annotation can be used for the basic configuration, the advanced configuration requires properties or yaml files.\n\n```properties\nzonky.test.database.type=auto                     # The type of embedded database to be created when replacing the data source.\nzonky.test.database.provider=default              # Provider to be used to create the underlying embedded database.\nzonky.test.database.refresh=never                 # Determines the refresh mode of the embedded database.\nzonky.test.database.replace=any                   # Determines what type of existing DataSource beans can be replaced.\n\nzonky.test.database.postgres.client.properties.*= # Additional PostgreSQL options used to configure the test data source.\nzonky.test.database.mssql.client.properties.*=    # Additional MSSQL options used to configure the test data source.\nzonky.test.database.mysql.client.properties.*=    # Additional MySQL options used to configure the test data source.\nzonky.test.database.mariadb.client.properties.*=  # Additional MariaDB options used to configure the test data source.\n```\n\nNote that the library includes [configuration metadata](embedded-database-spring-test/src/main/resources/META-INF/spring-configuration-metadata.json) that offer contextual help and code completion as users are working with Spring Boot's `application.properties` or `application.yml` files.\n\n### PostgreSQL Configuration\n\nThe following configuration keys are honored by all postgres providers:\n\n```properties\nzonky.test.database.postgres.initdb.properties.*= # Additional PostgreSQL options to pass to initdb command during the database initialization.\nzonky.test.database.postgres.server.properties.*= # Additional PostgreSQL options used to configure the embedded database server.\n```\n\n**Example configuration:**\n```properties\nzonky.test.database.postgres.client.properties.stringtype=unspecified\nzonky.test.database.postgres.initdb.properties.lc-collate=cs_CZ.UTF-8\nzonky.test.database.postgres.initdb.properties.lc-monetary=cs_CZ.UTF-8\nzonky.test.database.postgres.initdb.properties.lc-numeric=cs_CZ.UTF-8\nzonky.test.database.postgres.server.properties.shared_buffers=512MB\nzonky.test.database.postgres.server.properties.max_connections=100\n```\n\n### Using Docker Provider (default)\n\nThis is the default provider, so you do not have to do anything special,\njust use the `@AutoConfigureEmbeddedDatabase` annotation in its basic form without specifying any provider.\n\n```java\n@RunWith(SpringRunner.class)\n@AutoConfigureEmbeddedDatabase\npublic class DefaultProviderIntegrationTest {\n    // class body...\n}\n```\n\nNote that the Docker provider is especially useful if you need to use some database extensions,\nor if you want to prepare a custom docker image containing some test data.\nIn such cases, you can use any docker image compatible with the official docker images of the supported databases.\n\n#### Docker-provider specific configuration\n\nThe provider configuration can be managed via properties in the\n`zonky.test.database.postgres.docker`, `zonky.test.database.mysql.docker`, `zonky.test.database.mariadb.docker`\nand `zonky.test.database.mssql.docker` groups as shown below.\n\n```properties\nzonky.test.database.postgres.docker.image=postgres:11-alpine        # Docker image containing PostgreSQL database.\nzonky.test.database.postgres.docker.tmpfs.enabled=false             # Whether to mount postgres data directory as tmpfs.\nzonky.test.database.postgres.docker.tmpfs.options=rw,noexec,nosuid  # Mount options used to configure the tmpfs filesystem.\n\nzonky.test.database.mysql.docker.image=mysql:5.7                    # Docker image containing MySQL database.\nzonky.test.database.mysql.docker.tmpfs.enabled=false                # Whether to mount database data directory as tmpfs.\nzonky.test.database.mysql.docker.tmpfs.options=rw,noexec,nosuid     # Mount options used to configure the tmpfs filesystem.\n\nzonky.test.database.mariadb.docker.image=mariadb:10.4               # Docker image containing MariaDB database.\nzonky.test.database.mariadb.docker.tmpfs.enabled=false              # Whether to mount database data directory as tmpfs.\nzonky.test.database.mariadb.docker.tmpfs.options=rw,noexec,nosuid   # Mount options used to configure the tmpfs filesystem.\n\nzonky.test.database.mssql.docker.image=mcr.microsoft.com/mssql/server:2017-latest # Docker image containing MSSQL database.\n``` \n\nOr, the provider configuration can also be customized with a bean implementing `PostgreSQLContainerCustomizer` interface.\n\n```java\nimport io.zonky.test.db.config.PostgreSQLContainerCustomizer;\n\n@Configuration\npublic class EmbeddedPostgresConfiguration {\n    \n    @Bean\n    public PostgreSQLContainerCustomizer postgresContainerCustomizer() {\n        return container -\u003e container.withStartupTimeout(Duration.ofSeconds(60L));\n    }\n}\n```\n\n```java\n@RunWith(SpringRunner.class)\n@AutoConfigureEmbeddedDatabase\n@ContextConfiguration(classes = EmbeddedPostgresConfiguration.class)\npublic class EmbeddedPostgresIntegrationTest {\n    // class body...\n}\n```\n\n### Using Zonky Provider (previous default)\n\nBefore you use the Zonky provider, you have to add the following Maven dependency:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eio.zonky.test\u003c/groupId\u003e\n    \u003cartifactId\u003eembedded-postgres\u003c/artifactId\u003e\n    \u003cversion\u003e1.2.10\u003c/version\u003e\n    \u003cscope\u003etest\u003c/scope\u003e\n\u003c/dependency\u003e\n```\n\nThen, you can use the `@AutoConfigureEmbeddedDatabase` annotation to set up the `DatabaseProvider.ZONKY` provider.\n\n```java\n@RunWith(SpringRunner.class)\n@AutoConfigureEmbeddedDatabase(provider = ZONKY)\npublic class ZonkyProviderIntegrationTest {\n    // class body...\n}\n```\n\nNote that the Zonky provider can be useful as an alternative if you can't use Docker for some reason,\nand in version `1.x.x` it used to be the default provider.\n\n#### Changing the version of postgres binaries\n\nThe version of the binaries is configurable at compile time by importing `embedded-postgres-binaries-bom` in a required version into your dependency management section.\n\n```xml\n\u003cdependencyManagement\u003e\n    \u003cdependencies\u003e\n        \u003cdependency\u003e\n            \u003cgroupId\u003eio.zonky.test.postgres\u003c/groupId\u003e\n            \u003cartifactId\u003eembedded-postgres-binaries-bom\u003c/artifactId\u003e\n            \u003cversion\u003e13.2.0\u003c/version\u003e\n            \u003ctype\u003epom\u003c/type\u003e\n            \u003cscope\u003eimport\u003c/scope\u003e\n        \u003c/dependency\u003e\n    \u003c/dependencies\u003e\n\u003c/dependencyManagement\u003e\n```\n\nFind more information about this topic here: https://github.com/zonkyio/embedded-postgres#postgres-version\n\n#### Enabling support for additional architectures\n\nBy default, only the support for `amd64` architecture is enabled.\nSupport for other architectures can be enabled using the following instructions:\nhttps://github.com/zonkyio/embedded-postgres#additional-architectures\n\n#### Zonky-provider specific configuration\n\nThe provider configuration can be customized with a bean implementing `Consumer\u003cEmbeddedPostgres.Builder\u003e` interface.\nThe obtained builder provides methods to change the configuration before the database is started.\n\n```java\nimport io.zonky.test.db.postgres.embedded.EmbeddedPostgres;\n\n@Configuration\npublic class EmbeddedPostgresConfiguration {\n    \n    @Bean\n    public Consumer\u003cEmbeddedPostgres.Builder\u003e embeddedPostgresCustomizer() {\n        return builder -\u003e builder.setPGStartupWait(Duration.ofSeconds(60L));\n    }\n}\n```\n\n```java\n@RunWith(SpringRunner.class)\n@AutoConfigureEmbeddedDatabase(provider = ZONKY)\n@ContextConfiguration(classes = EmbeddedPostgresConfiguration.class)\npublic class EmbeddedPostgresIntegrationTest {\n    // class body...\n}\n```\n\n### Using OpenTable Provider\n\nBefore you use the OpenTable provider, you have to add the following Maven dependency:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003ecom.opentable.components\u003c/groupId\u003e\n    \u003cartifactId\u003eotj-pg-embedded\u003c/artifactId\u003e\n    \u003cversion\u003e0.13.1\u003c/version\u003e\n    \u003cscope\u003etest\u003c/scope\u003e\n\u003c/dependency\u003e\n```\n\nThen, you can use the `@AutoConfigureEmbeddedDatabase` annotation to set up the `DatabaseProvider.OPENTABLE` provider.\n\n```java\n@RunWith(SpringRunner.class)\n@AutoConfigureEmbeddedDatabase(provider = OPENTABLE)\npublic class OpenTableProviderIntegrationTest {\n    // class body...\n}\n```\n\n#### OpenTable-provider specific configuration\n\nThe provider configuration can be customized with a bean implementing `Consumer\u003cEmbeddedPostgres.Builder\u003e` interface.\nThe obtained builder provides methods to change the configuration before the database is being started.\n\n```java\nimport com.opentable.db.postgres.embedded.EmbeddedPostgres;\n\n@Configuration\npublic class EmbeddedPostgresConfiguration {\n    \n    @Bean\n    public Consumer\u003cEmbeddedPostgres.Builder\u003e embeddedPostgresCustomizer() {\n        return builder -\u003e builder.setPGStartupWait(Duration.ofSeconds(60L));\n    }\n}\n```\n\n```java\n@RunWith(SpringRunner.class)\n@AutoConfigureEmbeddedDatabase(provider = OPENTABLE)\n@ContextConfiguration(classes = EmbeddedPostgresConfiguration.class)\npublic class EmbeddedPostgresIntegrationTest {\n    // class body...\n}\n```\n\n### Using Yandex Provider\n\nBefore you use the Yandex provider, you have to add the following Maven dependency:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eru.yandex.qatools.embed\u003c/groupId\u003e\n    \u003cartifactId\u003epostgresql-embedded\u003c/artifactId\u003e\n    \u003cversion\u003e2.10\u003c/version\u003e\n    \u003cscope\u003etest\u003c/scope\u003e\n\u003c/dependency\u003e\n```\n\nThen, you can use the `@AutoConfigureEmbeddedDatabase` annotation to set up the `DatabaseProvider.YANDEX` provider.\n\n```java\n@RunWith(SpringRunner.class)\n@AutoConfigureEmbeddedDatabase(provider = YANDEX)\npublic class YandexProviderIntegrationTest {\n    // class body...\n}\n```\n\n#### Yandex-provider specific configuration\n\nThe provider configuration can be managed via properties in the `zonky.test.database.postgres.yandex-provider` group.\n\n```properties\nzonky.test.database.postgres.yandex-provider.postgres-version=11.10-1 # Version of EnterpriseDB PostgreSQL binaries (https://www.enterprisedb.com/download-postgresql-binaries).\n```\n\n## Advanced Topics\n\n### Database Prefetching\n\nThe 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 the `zonky.test.database.prefetching` group.\n\n```properties\nzonky.test.database.prefetching.thread-name-prefix=prefetching- # Prefix to use for the names of database prefetching threads.\nzonky.test.database.prefetching.concurrency=3                   # Maximum number of concurrently running database prefetching threads.\nzonky.test.database.prefetching.pipeline-cache-size=5           # Maximum number of prepared databases per pipeline.\nzonky.test.database.prefetching.max-prepared-templates=10       # Maximum number of prepared database templates.\n```\n\n### Disabling auto-configuration\n\nBy default, the library automatically registers all necessary context customizers and test execution listeners.\nIf this behavior is inappropriate for some reason, you can deactivate it by excluding the `embedded-database-spring-test-autoconfigure` dependency.\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eio.zonky.test\u003c/groupId\u003e\n    \u003cartifactId\u003eembedded-database-spring-test\u003c/artifactId\u003e\n    \u003cversion\u003e2.6.0\u003c/version\u003e\n    \u003cscope\u003etest\u003c/scope\u003e\n    \u003cexclusions\u003e\n        \u003cexclusion\u003e\n            \u003cgroupId\u003eio.zonky.test\u003c/groupId\u003e\n            \u003cartifactId\u003eembedded-database-spring-test-autoconfigure\u003c/artifactId\u003e\n        \u003c/exclusion\u003e\n    \u003c/exclusions\u003e\n\u003c/dependency\u003e\n```\n\n### Background bootstrapping mode\n\nThis 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.\nIn such case, a `DataSource` proxy is immediately returned for injection purposes instead of waiting for the bootstrapping to complete.\nHowever, note that the first actual call to a data source method will then block until the bootstrapping is completed, if not ready by then.\nFor maximum benefit, make sure to avoid early data source calls in init methods of related beans.\n\n## Troubleshooting\n\n### Connecting to the embedded database\n\nWhen 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:\n\n```log\ni.z.t.d.l.EmbeddedDatabaseReporter - JDBC URL to connect to 'dataSource1': url='jdbc:postgresql://localhost:55112/fynwkrpzfcyj?user=postgres', scope='TestClass#testMethod'\n```\n\n**TIP:** You can use the following **IntelliJ IDEA plugin to automatically synchronize the database settings** according to the connection strings in the log produced by the library:\nhttps://gist.github.com/tomix26/9e1ea63353707ef3b5cf4869fc50eec2\n\nNote that if you are using the [refresh mode](#refreshing-the-database-during-tests) 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.\n\n### Process [/tmp/embedded-pg/PG-XYZ/bin/initdb, ...] failed\n\nCheck the console output for the `initdb: 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.\n\nIf the error is not present, try to clean up the `/tmp/embedded-pg/PG-XYZ` directory containing temporary binaries of the embedded database.\n\n### Running tests on Windows does not work\n\nYou probably need to install [Microsoft Visual C++ 2013 Redistributable Package](https://support.microsoft.com/en-us/help/3179560/update-for-visual-c-2013-and-visual-c-redistributable-package). The 2013 version is important, installing other versions does not help. The problem is discussed in more detail [here](https://github.com/opentable/otj-pg-embedded/issues/65).\n\n### Running tests in Docker does not work\n\nRunning 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.  \n\nSo be sure to use a docker image that runs with a non-root user. Or, since version `1.5.5` you can run the docker container with the `--privileged` option, which allows to take advantage of the `unshare` command to run the database process in a separate namespace.\n\nBelow are some examples of how to prepare a docker image running with a non-root user:\n\n\u003cdetails\u003e\n  \u003csummary\u003eStandard Dockerfile\u003c/summary\u003e\n  \n  ```dockerfile\n  FROM openjdk:8-jdk\n  \n  RUN groupadd --system --gid 1000 test\n  RUN useradd --system --gid test --uid 1000 --shell /bin/bash --create-home test\n  \n  USER test\n  WORKDIR /home/test\n  ```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eAlpine Dockerfile\u003c/summary\u003e\n  \n  ```dockerfile\n  FROM openjdk:8-jdk-alpine\n  \n  RUN addgroup -S -g 1000 test\n  RUN adduser -D -S -G test -u 1000 -s /bin/ash test\n  \n  USER test\n  WORKDIR /home/test\n  ```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eGitlab runner Docker executor\u003c/summary\u003e\n\n  Configure the Docker container to run in privileged mode as described [here](https://docs.gitlab.com/runner/executors/docker.html#use-docker-in-docker-with-privileged-mode).\n\n  ```\n  [[runners]]\n    executor = \"docker\"\n    [runners.docker]\n      privileged = true\n  ```\n\n\u003c/details\u003e\n\n### Using Docker provider inside a Docker container\n\nThis combination is supported, however, additional configuration is required.\nYou have to add the `-v /var/run/docker.sock:/var/run/docker.sock` mapping to the Docker command to map the Docker socket.\nDetailed instructions can be found [here](https://www.testcontainers.org/supported_docker_environment/continuous_integration/dind_patterns/).\n\n### Frequent and repeated initialization of the database\n\nMake sure you do not use `org.flywaydb.test.junit.FlywayTestExecutionListener` or `org.flywaydb.test.FlywayTestExecutionListener` listeners. Because this library has its own test execution listener that can optimize database initialization.\nBut this optimization has no effect if any of these listeners is also applied.\n\n## Building from Source\nThe project uses a [Gradle](http://gradle.org)-based build system. In the instructions\nbelow, [`./gradlew`](http://vimeo.com/34436402) is invoked from the root of the source tree and serves as\na cross-platform, self-contained bootstrap mechanism for the build.\n\n### Prerequisites\n\n[Git](http://help.github.com/set-up-git-redirect) and [JDK 8 or later](http://www.oracle.com/technetwork/java/javase/downloads)\n\nBe sure that your `JAVA_HOME` environment variable points to the `jdk1.8.0` folder\nextracted from the JDK download.\n\n### Check out sources\n`git clone git@github.com:zonkyio/embedded-database-spring-test.git`\n\n### Compile and test\n`./gradlew build`\n\n## Project dependencies\n\n* [Spring Framework](https://spring.io/) (5.3.24) - `spring-test`, `spring-context` modules\n* [Testcontainers](https://www.testcontainers.org) (1.17.6)\n* [Cedarsoftware](https://github.com/jdereg/java-util) (1.68.0)\n* [Guava](https://github.com/google/guava) (24.1.1-jre)\n\n## License\nThe project is released under version 2.0 of the [Apache License](http://www.apache.org/licenses/LICENSE-2.0.html).\n","funding_links":[],"categories":["测试"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzonkyio%2Fembedded-database-spring-test","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzonkyio%2Fembedded-database-spring-test","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzonkyio%2Fembedded-database-spring-test/lists"}