我通常会这样做:
在@Before 方法中,我建立了与内存数据库的连接,如下所示:
@Before
public void setup()
{
this.dbConnection = DriverManager.getConnection("jdbc:hsqldb:mem:testcase;shutdown=true", "sa", null);
}
连接存储在实例变量中,因此可用于每个测试。
如果所有测试共享相同的表,我也会在 setup() 方法中创建这些表,否则每个测试都会创建自己的表:
@Test
public void foo()
{
Statement stmt = this.dbConnection.createStatement();
stmt.execute("create table foo (id integer)");
this.dbConnection.commit();
... now run the test
}
在@After 方法中,我简单地关闭了连接,这意味着内存数据库被擦除,下一个测试使用干净的版本运行:
@After
public void tearDown()
throws Exception
{
dbConnection.disconnect();
}
有时我确实需要在真正的数据库服务器上运行 unitt-tests(您无法使用 HSQLDB 或 H2 测试 Postgres 或 Oracle 的特定功能)。在这种情况下,我只为每个 Testclass 建立一次连接,而不是为每个测试方法建立一次连接。然后我有方法删除所有对象以清理架构。
这都可以放入一个小的实用程序类中,以避免一些样板代码。如果您想以某种方式外部化测试数据,Apache 的 DbUtils 和 DbUnit 也可以让生活变得更轻松。