我尝试使用dbunit来测试我的DAO。我们在与spring-test-dbunit不兼容的版本中使用Spring。我无法将我的dao bean自动装入我的测试类,因为那时我必须使用@RunWith(SpringJUnit4ClassRunner.class)
来关注一个无参数构造函数。我的班级如下:
public class DbUnitExample extends DBTestCase {
@Autowired
public MyDAO myDAO;
public DbUnitExample(String name) {
super(name);
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, "com.mysql.jdbc.Driver");
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, "...");
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, "...");
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, "...");
}
@Override
protected IDataSet getDataSet() throws Exception {
return new FlatXmlDataSetBuilder().build(new FileInputStream("target/partial.xml"));
}
@Override
protected DatabaseOperation getSetUpOperation() throws Exception {
return DatabaseOperation.REFRESH;
}
@Override
protected DatabaseOperation getTearDownOperation() throws Exception {
return DatabaseOperation.NONE;
}
@Test
public void testSometing() throws Exception {
myDAO.deleteById(12662);
}
}
当然我得到了一个NPE,因为我的dao bean无法找到。当我使用@RunWith(SpringJUnit4ClassRunner.class)
时,我需要提供一个无参数构造函数,并且必须删除我的" dbunit" -constructor。有没有使用spring-test-dbunit将dbunit与spring一起使用的标准方法或解决方法
修改
我的班级现在看起来如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/test-application.xml")
@DirtiesContext
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class })
public class DbUnitExample extends DBTestCase {
@Autowired
public MyDAO myDAO;
public DbUnitExample() {
super("target/partial.xml");
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, "com.mysql.jdbc.Driver");
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, "...");
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, "...");
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, "...");
}
@Override
protected IDataSet getDataSet() throws Exception {
return new FlatXmlDataSetBuilder().build(new FileInputStream("target/partial.xml"));
}
@Override
protected DatabaseOperation getSetUpOperation() throws Exception {
return DatabaseOperation.REFRESH;
}
@Override
protected DatabaseOperation getTearDownOperation() throws Exception {
// return DatabaseOperation.NONE;
// return DatabaseOperation.REFRESH;
return DatabaseOperation.CLEAN_INSERT;
}
@Test
public void testSometing() throws Exception {
myDAO.deleteById(12662);
}
}
它现在编译,但没有dbunt功能,这意味着如果我删除一行,它就不会恢复到之前的状态(再次插入)。
答案 0 :(得分:0)
由于您使用的是Spring,我建议将dbUnit实例自动装入测试中。 dbUnit Test Cases page为PrepAndExpectedTestCase
提供了“使用Spring的配置示例”,但只需复制代码并将其更改为DBTestCase
并进行相应调整。