簡體   English   中英

如何快速為Cucumber-jvm創建測試數據庫?

[英]how to quickly create a test database for Cucumber-jvm?

我正在使用Cucuming-jvm來測試我正在工作的舊系統的行為。 我必須使用Java 1.5和Hibernate 3.3,無法升級。 由於在測試過程中它將一些對象存儲在數據庫中,因此我創建了一個新的開發數據庫。

令我困擾的是,每次重新運行測試時,我必須手動刪除記錄(使用sql腳本),否則它們將失敗。 任何其他想要運行它們的人都必須這樣做。 我想通過以下任一方法快速自動清除測試數據庫:

  • 創建一個空數據庫並用我需要的數據庫填充它,或者
  • 使用已經存在的數據庫,在開始測試之前刪除記錄。

到目前為止,我所擁有的:我正在使用Cucumber-junit插件,並且RunTests類重定向到我的測試數據庫:

@RunWith(Cucumber.class)
@Cucumber.Options(
    features = "test/resources/cucumber",
    format = "html:target/cucumber"
)
public class RunTests {
    private static Configuration configuration;

    @BeforeClass
    public static void preparaBase() {
        // gets the mapped configuration to the db
        configuration = HibernateUtil.getConfiguration();

        configuration.setProperty("hibernate.connection.url", "test-db-url");
        configuration.setProperty("hibernate.connection.username", "user");
        configuration.setProperty("hibernate.connection.password", "pass");
//      configuration.setProperty("hibernate.hbm2ddl.auto", "create-drop");

        // rebuilds the configuration using my test database
        HibernateUtil.rebuildSessionFactory(configuration);
    }
}

我嘗試將hibernate.hbm2ddl.auto屬性與create-drop值一起使用,並使用import.sql文件准備數據庫,但是啟動測試花費了很多時間,而且似乎沒有檢測到我的import.sql文件。

可悲的是,使用Maven及其出色的maven-sql-plugin並不是一種選擇(我建議改用Maven,但無濟於事)。 還有其他選擇嗎?

我做的!

我這樣使用了ScriptRunner類:

@RunWith(Cucumber.class)
@Cucumber.Options(
    features = "test/resources/cucumber",
    format = "html:target/cucumber"
)
public class RunTests {
    private static Configuration configuration;
    String url = "test-db-url";
    String user = "user";
    String pass = "pass";

    @BeforeClass
    public static void preparaBase() {
        // gets the mapped configuration to the db
        configuration = HibernateUtil.getConfiguration();

        configuration.setProperty("hibernate.connection.url", url);
        configuration.setProperty("hibernate.connection.username", user);
        configuration.setProperty("hibernate.connection.password", pass);

        // rebuilds the configuration using my test database
        HibernateUtil.rebuildSessionFactory(configuration);

        // executes a script stored in test/resources/cucumber
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection(url, user, pass);
            ScriptRunner runner = new ScriptRunner(conn, false, true);

            runner.runScript(new BufferedReader(new FileReader("test/resources/cucumber/db.sql")));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

暫無
暫無

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

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