[英]Problems using dbunit with Spring (without spring-test-dbunit)
我正在嘗試使用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,因為找不到我的刀豆。 當我使用@RunWith(SpringJUnit4ClassRunner.class)
我需要提供一個無參數的構造函數,並且必須刪除我的“ dbunit”構造函數。 有沒有在不使用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功能,這意味着如果我刪除一行,它不會恢復到先前的狀態(再次插入)。
由於您使用的是Spring,因此建議將dbUnit實例自動裝配到測試中。 該DBUnit的測試用例頁面有“配置示例使用Spring”為PrepAndExpectedTestCase
,而只是復制代碼並將其更改為DBTestCase
並相應地調整。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.