【问题标题】:JUnit test, error related to transactionJUnit 测试,与事务相关的错误
【发布时间】:2012-03-11 15:03:59
【问题描述】:

我在项目中使用 spring、hibernate 和 maven。

我下面有一门课

@Service
public class  ServiceImpl implements Service ,Serializable{
   //Code
}

在这个类中,我有一个方法声明如下,

@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW, readOnly = false)
public void doSomething(Obj a, Obj b){
    //code
}

我对此方法进行了 JUnit 测试。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:com/mt/sm/application-context.xml", "classpath:com/mt/sm/security-context.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class ServiceImplTest {
    @Test
    public void testdoSomething() {
        //code
    }
}

我在下面遇到了这个错误

Testcase: testdoSomething(com.mt.sm.services.ServiceImplTest):  Caused an ERROR
Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly

但是以同样的方式,我声明了另一种方法来调用上面的方法

public void call (Obj a, Obj b) {
    doSomething(a,b);
}

@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW, readOnly = false)
public void doSomething(Obj a, Obj b){
    //code
}

对于结果,我可以进行测试。 我只是想问一下为什么它可以正常工作。

【问题讨论】:

    标签: hibernate spring maven junit


    【解决方案1】:

    Spring 通过 AOP 代理管理事务,所以内部调用永远不会是事务性的(你不能自己代理)

    【讨论】:

      猜你喜欢
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 2012-01-04
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多