我有一个junit测试类,其配置如下:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({ WebContextTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class })
@ActiveProfiles("test")
@DirtiesContext
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = {
SpringConfig.class, SpringTestingConfig.class,
SpringLocalContainerJPAConfig.class, CustomConfiguration.class })
并且测试方法正在调用服务方法,并且服务类由于某种原因而具有注释@Transactional
,当我为服务方法创建测试用例时它失败并给我异常org.hibernate.PersistentObjectException: detached entity passed to persist
,因为这个职位:
org.hibernate.PersistentObjectException: detached entity passed to persist with H2 in memory database
并且要修复此异常,我必须使用注释@Transactional
注释测试类,尽管在托管bean中,当我调用相同的代码时,它工作正常,所以我的问题是为什么有时在测试中需要@Transactional
考虑到服务层有这个注释,我应该用@Transactional
注释我的测试类。