我有一个类别 - > subCategory - >我的应用程序中的产品层次如果子类别没有产品,则允许您删除它。如果subCategory有产品,则DAO会抛出DataIntegrityViolationException,并且应该回滚该事务。
在我的测试中,我有:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestTransactionManagement.class})
public class BusinessSubCategoryCRUDTest {
@Autowired
public void setCRUD(BusinessSubCategoryCRUD crud) {
this.crud = crud;
}
// @Transactional
@Test
public void testDeleteBusinessSubCategoryInUseCanNotBeDeleted() {
final long id = 1;
BusinessSubCategory subCategoryBeforeDelete =
crud.readBusinessSubCategory(id);
final int numCategoriesBeforeDelete =
subCategoryBeforeDelete.getBusinessCategories().size();
try {
crud.deleteBusinessSubCategory(
new BusinessSubCategory(id, ""));
} catch (DataIntegrityViolationException e) {
System.err.println(e);
}
BusinessSubCategory subCategoryAfterDeleteFails =
crud.readBusinessSubCategory(id);
// THIS next assertion is the source of my angst.
// At this point the the links to the categories will have been
// been deleted, an exception will have been thrown but the
// Transaction is not yet rolled back if the test case (or test
// class) is marked with @Transactional
assertEquals(
numCategoriesBeforeDelete,
subCategoryAfterDeleteFails.getBusinessCategories().size());
}
}
但是,如果我取消注释@Test上方的@Transactional,则会失败。我认为DAO正在使用来自@Test的事务,因此在我检查以确保事务已回滚之前,事务不会回滚。
@Transactional(readOnly = false, propagation =
Propagation.REQUIRED)
public boolean deleteBusinessSubCategory(
BusinessSubCategory businessSubCategory) {
BeanPropertySqlParameterSource paramMap = new
BeanPropertySqlParameterSource(businessSubCategory);
namedJdbcTemplate.update(
DELETE_CATEGORY_SUB_CATEGORY_BY_ID_SQL,
paramMap);
return 0 != namedJdbcTemplate.update(
DELETE_SUB_CATEGORY_BY_ID_SQL,
paramMap);
}
那么,我如何让DAO代码仍然从它运行的上下文继承事务(在生产中它从它运行的服务继承事务)但仍然能够测试它。我想将@Transactional放在整个测试类中,但这会使我的测试失败或不完整。
为了完整性,这是我的测试配置类。
@Configuration
@EnableTransactionManagement
public class TestTransactionManagement {
@Bean
public EmbeddedDatabase getDataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase db = builder
.setType(EmbeddedDatabaseType.HSQL) //.H2 or .DERBY
.addScript("sql/create-db.sql")
.addScript("sql/create-test-data.sql")
.build();
return db;
}
@Bean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(getDataSource());
}
@Bean
public BusinessSubCategoryCRUD getCRUD() {
return new BusinessSubCategoryCRUD(getDataSource());
}
}