【问题标题】:Junit and Jmock to test Springs TransactionSynchronizationManagerJunit 和 Jmock 测试 Springs TransactionSynchronizationManager
【发布时间】:2014-01-02 18:21:00
【问题描述】:

我有一些使用事务同步管理器的代码.. 但我似乎无法让它在模拟中工作.. 我在模拟实体管理器和事务管理器.. 以便我的上下文保存一个实体并调用提交... TransactionSynchronizationManager 在测试中似乎没有受到打击?

   this.transactionTemplate.execute(new TransactionCallback<E>() {
                @Override
                public E doInTransaction(TransactionStatus status) {    
                    // update entities


                    TransactionSynchronizationManager.registerSynchronization(new NotificationTransactionSynchronization(){
                       @Override
                       public void afterCommit() {
                    // do some post commit work
                                   int i = notifier.notifyAllListeners();
                       }
                    });

                }
            });

我的测试课:

@Test
public void testHappyPath() {


    context.checking(new Expectations() {
        {
            allowing(platformTransactionManager).getTransaction(definition);
            will((returnValue(status)));

            oneOf(platformTransactionManager).commit(status);

                         //next line never gets hit... so the test fails...
                         //if i remove it will pass but i need to check that it works...

            oneOf(mockNotifier).notifyAllListeners();

        }
    });
    this.TestClass.process();
    context.assertIsSatisfied();            
}   

【问题讨论】:

  • 请清理您的帖子
  • 嗯?...如何...更多信息...更好的格式?...
  • 现在由 Don Roby 格式化

标签: java spring jmock


【解决方案1】:

最近,我不得不测试使用事务挂钩的代码,经过一番调查,我得到了以下解决方案:

源代码:

public void methodWithTransactionalHooks() {

    //...

    TransactionSynchronizationManager.registerSynchronization(
        new TransactionSynchronizationAdapter() {
            public void afterCommit() { 
                // perform after commit synchronization
            }
        }
    );

    //...
}

测试:

@Transactional
@Test
public void testMethodWithTransactionalHooks() {

    // prepare test

    // fire transaction synchronizations explicitly
    for(TransactionSynchronization transactionSynchronization 
        : TransactionSynchronizationManager.getSynchronizations()
    ){
        transactionSynchornization.afterCommit();
    }

    // verify results
}

默认情况下测试设置为回滚,因此不会触发 afterCommit 同步。要对其进行测试,需要显式调用。

【讨论】:

    【解决方案2】:

    我不确定我是否理解,但如果您有一个模拟事务管理器,那么谁会调用通知器?

    【讨论】:

    • 是的,你是对的,我认为 mock 仍然会被外部的东西调用,然后会调用 sync..manager。
    【解决方案3】:

    我遇到了同样的问题,在我的情况下添加

    @Rollback(false)
    

    对测试方法有帮助。

    https://stackoverflow.com/a/9817815/1099376

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多