2013-08-23 75 views
4

我正在使用cucumber-jvm來測試我正在工作的遺留系統的行爲。我必須使用Java 1.5和Hibernate 3.3,升級不是一種選擇。因爲在我的測試中,它將一些對象存儲在數據庫中,所以我創建了一個新的開發數據庫。如何快速爲Cucumber-jvm創建測試數據庫?

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

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

我有什麼至今:我使用的是黃瓜的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,無濟於事)。有其他選擇嗎?

回答

1

我做到了!

我用這個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); 
     } 
    } 
}