gpt4 book ai didi

java - TransactionSynchronizationManager 内的单元测试代码

转载 作者:行者123 更新时间:2023-11-30 02:20:37 37 4
gpt4 key购买 nike

我找不到有效的解决方案,如何对 TransactionSynchronizationManager.registerSynchronization() 内部发生的事情进行单元测试。我有这样的代码:

pubclic class MyService {
public void method() {
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter()
{
@Override
public void afterCommit()
{
myService.callSmth(params);
}
}
}
}

这里我调用method():

public class MyClass {

private MyService myService;

public void method2() {
myService.method();
}
}

在我的单元测试中,我需要验证 myService.callSmth。但似乎测试代码没有进入 afterCommit() 方法。这是我的测试类:

@Configurable
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:test-applicationContext.xml" })
public class ServiceTest extends TestHelper
{
@Mock
MyService myService;

@InjectMocks
MyClass myClass;

@Test
public void allowWriteOffGlobal()
{
myClass.method();
veryfy(myService).method();
}
}

我简化了我的代码,请不要注意模拟和类似的错误。在调试器中,我看到流程如何到达 TransactionSynchronizationManager.registerSynchronization 行并跳过 afterCommit() 方法。P.s.:不确定我提供了足够的信息。如果有额外的需要,请在评论中写下。谢谢。

最佳答案

来自Spring Test documentation (强调我的):

Annotating a test method with @Transactional causes the test to be run within a transaction that will, by default, be automatically rolled back after completion of the test. If a test class is annotated with @Transactional, each test method within that class hierarchy will be run within a transaction. Test methods that are not annotated with @Transactional (at the class or method level) will not be run within a transaction. Furthermore, tests that are annotated with @Transactional but have the propagation type set to NOT_SUPPORTED will not be run within a transaction.

By default, test transactions will be automatically rolled back after completion of the test; however, transactional commit and rollback behavior can be configured declaratively via the @Commit and @Rollback annotations at the class level and at the method level.

所以我建议在您的测试方法中添加一个@Commit注释。 (根据您描述的行为,我认为您正在使用 Spring Test,否则此建议不适用)。

关于java - TransactionSynchronizationManager 内的单元测试代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46951310/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com