Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 在JUnit5测试类之间共享数据库连接_Spring_Spring Boot_Junit_Junit5_Spring Test - Fatal编程技术网

Spring 在JUnit5测试类之间共享数据库连接

Spring 在JUnit5测试类之间共享数据库连接,spring,spring-boot,junit,junit5,spring-test,Spring,Spring Boot,Junit,Junit5,Spring Test,我将6个JUnit类放入不同的测试包中。我想使用Spring框架用来设置数据库连接的application.properties文件 问题是如何在运行第一个JUnit测试时创建数据库连接,并对所有类重用它。最后,请正确关闭连接。您可以使用。如果要重用现有数据库容器(例如PostgreSQL或MySQL),请确保使用手动容器生命周期方法并启动容器一次(例如在抽象测试类中)。Testcontainers称之为: 一旦JVM终止,容器将被删除 另一种方法是: 如果您的数据库设置与所有测试相似,并且您选

我将6个JUnit类放入不同的测试包中。我想使用Spring框架用来设置数据库连接的
application.properties
文件

问题是如何在运行第一个JUnit测试时创建数据库连接,并对所有类重用它。最后,请正确关闭连接。

您可以使用。如果要重用现有数据库容器(例如PostgreSQL或MySQL),请确保使用手动容器生命周期方法并启动容器一次(例如在抽象测试类中)。Testcontainers称之为:

一旦JVM终止,容器将被删除

另一种方法是:


如果您的数据库设置与所有测试相似,并且您选择使用此功能,Testcontainers将重用已启动的容器。请记住,使用这种方法,您必须自己清理容器,因为在所有测试完成后,容器仍保持活动状态。

不幸的是,我正在使用MSSQL服务器处理此数据库?这没有问题,Testcontainers也有一个新的功能。
abstract class AbstractContainerBaseTest {

    static final MySQLContainer MY_SQL_CONTAINER;

    static {
        MY_SQL_CONTAINER = new MySQLContainer();
        MY_SQL_CONTAINER.start();
    }
}

class FirstTest extends AbstractContainerBaseTest {

    @Test
    void someTestMethod() {
        String url = MY_SQL_CONTAINER.getJdbcUrl();

        // create a connection and run test as normal
    }
}
static PostgreSQLContainer postgreSQLContainer = (PostgreSQLContainer) new PostgreSQLContainer()
  .withDatabaseName("test")
  .withUsername("duke")
  .withPassword("s3cret")
  .withReuse(true);