为了保持JUnit测试之间的独立性,我需要在每次测试开始时创建数据库,并在每次测试结束时销毁它。
应该通过执行存在于H2文件中的SQL查询(原生插入查询...)在内存( SQL数据库)中创建数据库。
在属性文件中定义我的键值并遵守JPA规范(persistence.xml),我如何使用注释/注入为每个JUnit测试创建-删除数据库?
非常感谢!
发布于 2014-01-21 18:03:54
您应该能够使用Spring的嵌入式数据库配置来指定H2数据源(也显示为here):
<jdbc:embedded-database id="dataSource" type="H2">
<!-- Modify locations appropriately for your environment -->
<jdbc:script location="classpath:db-schema.sql"/>
<jdbc:script location="classpath:db-test-data.sql"/>
</jdbc:embedded-database>这应该放在特定于测试的testApplicationContext.xml中,并带有适当的名称空间声明。
当Spring在测试套件(测试类)的开始部分显示测试应用程序上下文时,它将创建H2数据源。因为Spring在测试类的持续时间内缓存应用程序上下文,所以您可以使用@DirtiesContext注释测试类,以便为每个测试方法重新创建应用程序上下文并重新初始化数据源:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:/your/testApplicationContext.xml"})
@DirtiesContext(classMode=ClassMode.AFTER_EACH_TEST_METHOD)
public class SomeDatabaseTest {
@Autowired
private SomeDao dao;
// Test methods
}有关Spring的嵌入式数据库功能的更多信息,请访问here
发布于 2014-01-22 13:24:15
您可能应该使用JPA或Spring特性,但这只是为了完整性:
在数据库端,H2支持running init scripts when opening the database,如下所示:
jdbc:h2:mem:test;INIT=runscript from '~/create.sql'或
jdbc:h2:mem:test;INIT=runscript from 'classpath:/com/acme/create.sql'当您关闭内存中的数据库(如上面的示例)时,数据将被删除。或者,您可以运行SQL语句drop all objects。
发布于 2014-01-21 18:33:13
https://stackoverflow.com/questions/21246802
复制相似问题