2

トランザクション同期マネージャーを使用するコードがいくつかありますが、モックで機能させることができないようです。エンティティマネージャーとトランザクションマネージャーをモックして、コンテキストがエンティティを保存し、commitを呼び出すようにします...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();            
}   
4

3 に答える 3

8

最近、トランザクションフックを使用しているコードをテストする必要があり、いくつかの調査の後、次の解決策にたどり着きました:

ソース:

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 同期は発生しません。テストするには、明示的な呼び出しが必要です。

于 2013-08-23T17:47:38.063 に答える
1

理解できるかどうかはわかりませんが、模擬トランザクションマネージャーがある場合、誰が通知機能を呼び出すのでしょうか。

于 2013-02-28T12:06:35.007 に答える
0

I ran into the same issue, in my case adding

@Rollback(false)

to the test method helped.

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

于 2014-01-02T10:21:00.243 に答える