将 DbUnit 与 Spring TestContext 结合使用时出现问题
我正在尝试分离地测试我的 DAO 层(基于 JPA 构建)。在单元测试中,我使用 DbUnit 填充数据库,并使用 Spring Test 获取 ApplicationContext 的实例。
当我尝试使用 SpringJunit4ClassRuner 时,ApplicationContext 被注入,但 DbUnit 的 getDataSet() 方法从未被调用。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/testdao.xml")
public class SimpleJPATest extends DBTestCase implements ApplicationContextAware {
...
然后我尝试删除 @RunWith 注释,这消除了 getDataSet() 方法的问题。但现在我不再注入 ApplicationContext 实例。我尝试使用 @TestExecutionListeners 注释,默认情况下它应该配置 DependencyInjectionTestExecutionListener,但 AppContext 仍然没有被注入。
@TestExecutionListeners
@ContextConfiguration(locations = "/testdao.xml")
public class SimpleJPATest extends DBTestCase implements ApplicationContextAware {
...
有人有什么想法吗?将这两个框架结合起来通常是一个坏主意吗?
编辑:这是测试类的其余源代码:
@TestExecutionListeners
@ContextConfiguration(locations = "/testdao.xml")
public class SimpleJPATest extends DBTestCase implements ApplicationContextAware {
static final String TEST_DB_PROPS_FILE = "testDb.properties";
static final String DATASET_FILE = "testDataSet.xml";
static Logger logger = Logger.getLogger( SimpleJPATest.class );
private ApplicationContext ctx;
public SimpleJPATest() throws Exception {
super();
setDBUnitSystemProperties(loadDBProperties());
}
@Test
public void testSimple() {
EntityManagerFactory emf = ctx.getBean("entityManagerFactory", EntityManagerFactory.class);
EntityManager em = emf.createEntityManager();
GenericDAO<Club> clubDAO = new JpaGenericDAO<Club>(ClubEntity.class, "ClubEntity", em);
em.getTransaction().begin();
Collection<Club> allClubs = clubDAO.findAll();
em.getTransaction().commit();
assertEquals(1, allClubs.size());
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.ctx = applicationContext;
}
private void setDBUnitSystemProperties(Properties props) {
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS,
props.getProperty("db.driver"));
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL,
props.getProperty("db.url"));
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME,
props.getProperty("db.username"));
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD,
props.getProperty("db.password"));
}
private Properties loadDBProperties() throws Exception {
URL propsFile = ClassLoader.getSystemResource(TEST_DB_PROPS_FILE);
assert (propsFile != null);
Properties props = new Properties();
props.load(propsFile.openStream());
return props;
}
@Override
protected void setUpDatabaseConfig(DatabaseConfig config) {
config.setProperty( DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
new HsqldbDataTypeFactory() );
}
@Override
protected DatabaseOperation getSetUpOperation() throws Exception {
return DatabaseOperation.CLEAN_INSERT;
}
@Override
protected DatabaseOperation getTearDownOperation() throws Exception {
return DatabaseOperation.DELETE_ALL;
}
@Override
protected IDataSet getDataSet() throws Exception {
logger.debug("in getDataSet");
URL dataSet = ClassLoader.getSystemResource(DATASET_FILE);
assert (dataSet != null);
FlatXmlDataSet result = new FlatXmlDataSetBuilder().build(dataSet);
return result;
}
}
I'm trying to test my DAO layer (which is built on JPA) in separation. In the unit test, I'm using DbUnit to populate the database and Spring Test to get an instance of ApplicationContext.
When I tried to use the SpringJunit4ClassRuner, the ApplicationContext got injected, but the DbUnit's getDataSet() method never got called.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/testdao.xml")
public class SimpleJPATest extends DBTestCase implements ApplicationContextAware {
...
Then I tried to remove the @RunWith annotation, that removed the problems with getDataSet() method. But now I no longer get ApplicationContext instance injected. I tried to use the @TestExecutionListeners annotation, which is supposed to configure the DependencyInjectionTestExecutionListener by default, but the AppContext still doesn't get injected.
@TestExecutionListeners
@ContextConfiguration(locations = "/testdao.xml")
public class SimpleJPATest extends DBTestCase implements ApplicationContextAware {
...
Does anyone have any ideas? Is it generally a bad idea to combine these two frameworks?
EDIT: here is the rest of the source for the test class:
@TestExecutionListeners
@ContextConfiguration(locations = "/testdao.xml")
public class SimpleJPATest extends DBTestCase implements ApplicationContextAware {
static final String TEST_DB_PROPS_FILE = "testDb.properties";
static final String DATASET_FILE = "testDataSet.xml";
static Logger logger = Logger.getLogger( SimpleJPATest.class );
private ApplicationContext ctx;
public SimpleJPATest() throws Exception {
super();
setDBUnitSystemProperties(loadDBProperties());
}
@Test
public void testSimple() {
EntityManagerFactory emf = ctx.getBean("entityManagerFactory", EntityManagerFactory.class);
EntityManager em = emf.createEntityManager();
GenericDAO<Club> clubDAO = new JpaGenericDAO<Club>(ClubEntity.class, "ClubEntity", em);
em.getTransaction().begin();
Collection<Club> allClubs = clubDAO.findAll();
em.getTransaction().commit();
assertEquals(1, allClubs.size());
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.ctx = applicationContext;
}
private void setDBUnitSystemProperties(Properties props) {
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS,
props.getProperty("db.driver"));
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL,
props.getProperty("db.url"));
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME,
props.getProperty("db.username"));
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD,
props.getProperty("db.password"));
}
private Properties loadDBProperties() throws Exception {
URL propsFile = ClassLoader.getSystemResource(TEST_DB_PROPS_FILE);
assert (propsFile != null);
Properties props = new Properties();
props.load(propsFile.openStream());
return props;
}
@Override
protected void setUpDatabaseConfig(DatabaseConfig config) {
config.setProperty( DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
new HsqldbDataTypeFactory() );
}
@Override
protected DatabaseOperation getSetUpOperation() throws Exception {
return DatabaseOperation.CLEAN_INSERT;
}
@Override
protected DatabaseOperation getTearDownOperation() throws Exception {
return DatabaseOperation.DELETE_ALL;
}
@Override
protected IDataSet getDataSet() throws Exception {
logger.debug("in getDataSet");
URL dataSet = ClassLoader.getSystemResource(DATASET_FILE);
assert (dataSet != null);
FlatXmlDataSet result = new FlatXmlDataSetBuilder().build(dataSet);
return result;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我一起使用这两个框架没有任何问题。我必须做一些与标准略有不同的事情,但要让它工作:
我必须做一些比我想要的更手动的事情,但是如果您尝试使用 JUnit 参数化,则同样的情况适用使用 Spring 运行(在这种情况下,您必须手动启动 TextContext)。最需要注意的是,我重写了 closeConnection() 方法并将其留空。这会覆盖每次测试后关闭数据源连接的默认操作,这可能会增加不必要的时间,因为每次测试后都必须重新打开连接。
I've used these two frameworks together without any issues. I've had to do some things a little different from the standard though to get it to work:
I've had to do things a little more manual than I would like, but the same scenario applies if you try to use the JUnit Parameterized runner with Spring (in that case you have to start the TextContext manually). The most important thing to note is that I override the closeConnection() method and leave it blank. This overrides the default action of closing the dataSource connection after each test which can add unnecessary time as the connection will have to be reopened after every test.