我目前正在使用DBUnit与Spring一起进行单元测试我的应用程序,但遇到了一个问题,我的更新逻辑测试总是失败,因为数据库发生了死锁,我无法弄清楚为什么会出现这种情况。请注意,我已经能够通过删除由@After注释的方法来解决这个问题,因为我正在使用@TransactionConfiguration注释,所以我真的不需要,但是我担心我会误解一些关于如何使用事务处理工作,因此我希望有人可以指出为什么我在运行updateTerritory方法时总是得到以下异常。
java.sql.SQLTransactionRollbackException: A lock could not be obtained within the time requested
有一点可能有助于指出我可以执行其他操作,例如查询数据库和插入新记录而不会出现任何锁定错误。另外我使用的是OpenJPA,spring正在将PersistenceUnit注入到我的DAO中。我猜测混合PersistenceUnit的使用以及在我的DBUnit设置代码(testSetup和testTeardown)中直接使用数据源可能是问题的一部分。我目前正在使用Derby作为我的数据库。
我的代码如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext.xml")
@TransactionConfiguration(defaultRollback = true)
public class TerritoryZoneManagerTest {
@Autowired
private DataSource unitTestingDataSource;
@Autowired
private ITerritoryZoneDaoManager mgr;
@Before
public void testSetup() throws DatabaseUnitException, SQLException,
FileNotFoundException {
Connection con = DataSourceUtils.getConnection(unitTestingDataSource);
IDatabaseConnection dbUnitCon = new DatabaseConnection(con);
FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
IDataSet dataSet = builder
.build(new FileInputStream(
"./src/com.company.territoryzonelookup/dao/test/TerritoryZoneManagerTest.xml"));
try {
// NOTE: There is no need to use the DatabaseOperation.DELETE
// functionality because spring will automatically remove all
// inserted records after each test case is executed.
DatabaseOperation.REFRESH.execute(dbUnitCon, dataSet);
} finally {
DataSourceUtils.releaseConnection(con, unitTestingDataSource);
}
}
@After
public void testTeardown() throws DatabaseUnitException, SQLException,
FileNotFoundException {
Connection con = DataSourceUtils.getConnection(unitTestingDataSource);
IDatabaseConnection dbUnitCon = new DatabaseConnection(con);
FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
IDataSet dataSet = builder
.build(new FileInputStream(
"./src/com.company.territoryzonelookup/dao/test/TerritoryZoneManagerTest.xml"));
try {
// NOTE: There is no need to use the DatabaseOperation.DELETE
// functionality because spring will automatically remove all
// inserted records after each test case is executed.
DatabaseOperation.DELETE.execute(dbUnitCon, dataSet);
} finally {
DataSourceUtils.releaseConnection(con, unitTestingDataSource);
}
}
@Test
@Transactional
public void updateTerritory() {
TerritoryZone zone = new TerritoryZone();
int id = 1;
zone = mgr.getTerritory(id);
String newCity = "Congerville";
zone.setCity(newCity);
mgr.updateTerritory(zone);
zone = mgr.getTerritory(id);
Assert.assertEquals(newCity, zone.getCity());
}
}
下面提供了DAO对象,以防有用。
@Repository
public class TerritoryZoneDaoManager implements ITerritoryZoneDaoManager {
/*
@Autowired
private EntityManagerFactory emf;
*/
/*
* @PersistenceUnit EntityManagerFactory emf;
*
* @PersistenceContext private EntityManager getEntityManager(){ return
* emf.createEntityManager(); }
*/
@PersistenceContext
private EntityManager em;
private EntityManager getEntityManager() {
// return emf.createEntityManager();
return em;
}
/* (non-Javadoc)
* @see com.company.territoryzonelookup.dao.ITerritoryZoneManager#addTerritory(com.company.territoryzonelookup.dao.TerritoryZone)
*/
@Override
public TerritoryZone addTerritory(TerritoryZone territoryZone) {
EntityManager em = getEntityManager();
em.persist(territoryZone);
return territoryZone;
}
/* (non-Javadoc)
* @see com.company.territoryzonelookup.dao.ITerritoryZoneManager#getTerritory(int)
*/
@Override
public TerritoryZone getTerritory(int id) {
TerritoryZone obj = null;
Query query = getEntityManager().createNamedQuery("selectById");
query.setParameter("id", id);
obj = (TerritoryZone) query.getSingleResult();
return obj;
}
/* (non-Javadoc)
* @see com.company.territoryzonelookup.dao.ITerritoryZoneManager#updateTerritory(com.company.territoryzonelookup.dao.TerritoryZone)
*/
@Override
public TerritoryZone updateTerritory(TerritoryZone territoryZone){
getEntityManager().merge(territoryZone);
return territoryZone;
}
/* (non-Javadoc)
* @see com.company.territoryzonelookup.dao.ITerritoryZoneManager#getActiveTerritoriesByStateZipLob(java.lang.String, java.lang.String, java.util.Date, java.lang.String)
*/
@Override
public List<TerritoryZone> getActiveTerritoriesByStateZipLob(String stateCd, String zipCode, Date effectiveDate, String lobCd){
List<TerritoryZone> territoryList;
Query query = getEntityManager().createNamedQuery("selectActiveByZipStateLob");
query.setParameter("zipCode", zipCode);
query.setParameter("state", stateCd);
query.setParameter("lob",lobCd);
query.setParameter("effectiveDate", effectiveDate);
territoryList = (List<TerritoryZone>) query.getResultList();
return territoryList;
}
/* (non-Javadoc)
* @see com.company.territoryzonelookup.dao.ITerritoryZoneManager#deleteAll()
*/
@Override
public void deleteAll(){
Query query = getEntityManager().createNativeQuery("Delete from TerritoryZone");
query.executeUpdate();
}
/***
* the load method will remove all existing records from the database and then will reload it using it the data passed.
* @param terrList
*/
public void load(List<TerritoryZone> terrList){
deleteAll();
for (TerritoryZone terr:terrList){
addTerritory(terr);
}
}
}
预先感谢您的协助。 杰里米
答案 0 :(得分:1)
jwmajors81
由于缺乏一些细节,我无法知道您的单元测试代码有什么问题。
我还使用了spring unit test和dbunit作为我的himvc框架,一个基于spring3和hibernate的RAD框架。这是我的超级单元测试代码,
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:config/application-test-config.xml"})
@Transactional
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public class HiMVCTransactionalUnitTest extends AbstractTransactionalJUnit4SpringContextTests{
@Autowired
protected DBUnitHelper dbHelper;
protected void loadFixture(){
try{
String fixtureFile=this.dbHelper.getDataFile();
if(fixtureFile==null){
fixtureFile=this.getDefaultXMLFixtureFile();
this.dbHelper.setDataFile(fixtureFile);
}
if(this.dbHelper.isDataFileExisted()){
if(this.dbHelper.isMSSQL()){
HiMVCInsertIdentityOperation operation=new HiMVCInsertIdentityOperation(DatabaseOperation.CLEAN_INSERT);
operation.setInTransaction(true);
this.dbHelper.executeDBOperation(operation);
}else{
this.dbHelper.executeDBOperation(DatabaseOperation.CLEAN_INSERT);
}
}
}catch(Exception x){
x.printStackTrace();
}
}
...
}
我在类声明中使用@Transactional注释,并且还指定了transactionManager。我写了一个DBUnitHelper来包装数据加载的dbunit细节。
这是一个单元测试样本:
public class MyTest extends HiMVCTransactionalUnitTest{
@Before
public void setup(){
super.loadFixture();
}
//other testing methods
}
希望这些代码有用。