我正在使用cucumber-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,但无济于事)。还有其他选择吗?
答案 0 :(得分:2)
我做到了!
我使用了这个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);
}
}
}