没有Spring/Hibernate的HSQL/H2的Junit

Sri*_*aul 7 java junit unit-testing h2 hsqldb

我正在尝试使用H2或HSQL进行单元测试.但我的应用程序不是春天和休眠.似乎大多数引用只有在内存db中用于HSQL/H2的spring和hibernate用于单元测试.

有人可以指向一个正确的引用,其中只有hsql/h2与junit一起使用吗?感谢你的时间.

a_h*_*ame 12

我通常做这样的事情:

在@Before方法中,我建立了与内存数据库的连接,如下所示:

@Before
public void setup()
{
   this.dbConnection = DriverManager.getConnection("jdbc:hsqldb:mem:testcase;shutdown=true", "sa", null);
}
Run Code Online (Sandbox Code Playgroud)

连接存储在实例变量中,因此可用于每个测试.

然后,如果所有测试共享相同的表,我也会在setup()方法中创建它们,否则每个测试都会创建自己的表:

@Test
public void foo()
{
   Statement stmt = this.dbConnection.createStatement();
   stmt.execute("create table foo (id integer)");
   this.dbConnection.commit();
   ... now run the test
}
Run Code Online (Sandbox Code Playgroud)

在@After方法中,我简单地关闭连接,这意味着内存数据库被擦除,下一个测试运行一个干净的版本:

@After
public void tearDown() 
  throws Exception
{
   dbConnection.disconnect();
}
Run Code Online (Sandbox Code Playgroud)

有时我确实需要再次运行unitt-testss一个真正的数据库服务器(你无法使用HSQLDB或H2测试Postgres或Oracle特定功能).在这种情况下,我只为每个Testclass建立一次连接,而不是每个测试方法一次.然后我有方法删除所有对象以清理模式.

这可以全部放入一个小实用程序类中,以避免一些样板代码.如果你想以某种方式外化测试数据,Apache的DbUtils也可以让生活更轻松,DbUnit也是如此.