簡體   English   中英

如何在 JUnit 測試容器中的 MySQLContainer 中導入 sql 轉儲文件

[英]How to import sql dump file in MySQLContainer in JUnit test containers

我有一個 Mysql 的測試容器,我需要在容器啟動后導入轉儲文件。 我嘗試了以下兩種選擇。

public class AbstractTest {

    public static MySQLContainer<?> mySQLContainer = new MySQLContainer<>("mysql:5.7");

    static {
        mySQLContainer
            .withDatabaseName("myDatabase")
            .withCopyFileToContainer(
                MountableFile.forClasspathResource("init.sql", 0744),
                "init.sql")
            .withUsername("root")
            .withPassword("root")
            .start();
    }

    @PostConstruct
    @SneakyThrows
    public void init() {
       option 1 // mySQLContainer.execInContainer("mysql -u root -proot myDatabase < init.sql");
       option 2 // mySQLContainer.execInContainer("mysql", "-u", "root", "-proot", "myDatabase", "<", "init.sql");
    }
   ////
}

仍然沒有成功 - 看起來 mysql 無法正確解析我的命令,如果我得到下一個答案:

mysql  Ver 14.14 Distrib 5.7.35, for Linux (x86_64) using  EditLine wrapper
Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Usage: mysql [OPTIONS] [database]
  -?, --help          Display this help and exit.
  -I, --help          Synonym for -?
  --auto-rehash       Enable automatic rehashing. One doesn't need to use
                      'rehash' to get table and field completion, but startup
////.....

如果使用下一個命令

  option 2 // mySQLContainer.execInContainer("mysql", "-u", "root", "-proot");

它工作正常,但這不是我想要的

如果我只是從 cli 通過 bash 連接到容器, mysql -u root -proot mydatabase < init.sql命令可以正常工作。

所以我的問題 - 如何通過執行圖像中的命令在 JUnit 測試容器中的 MySQLContainer 中導入 SQL 轉儲文件?

更新:我發現解析“<”符號有問題。 所以,基本上這在 CLI 中可以正常工作:

docker exec -i  mycontainer mysql -uroot -proot myDatabase < init.sql

但這不適用於 Java:

mySQLContainer.execInContainer("mysql","-uroot","-proot","myDatabase","<","init.sql");

您需要一個適用於MySql的 applications.properties,例如:

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
spring.datasource.driver-class-name =com.mysql.jdbc.Driver
#spring.jpa.show-sql: true

然后你可以在你的 /src/test/resources 中添加一個data.sql ,它會自動運行。

MySQL 可以自動加載轉儲文件,如果你把它放在一個特殊的路徑。

來自MySQL Docker 圖像的文檔:

首次啟動容器時,將使用提供的配置變量創建並初始化具有指定名稱的新數據庫。 此外,它將執行 /docker-entrypoint-initdb.d 中的 extensions.sh、.sql 和.sql.gz 文件。 文件將按字母順序執行。 您可以通過將 SQL 轉儲安裝到該目錄中輕松填充 mysql 服務,並提供帶有貢獻數據的自定義圖像。 SQL 文件將默認導入到 MYSQL_DATABASE 變量指定的數據庫中。

所以最簡單的方法是將文件復制到那里,如下所示:

.withCopyFileToContainer(MountableFile.forClasspathResource("init.sql"), "/docker-entrypoint-initdb.d/schema.sql")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM