如何对使用 TransactionTemplate.execute 的方法进行单元测试并验证在execute() 中执行的代码

问题描述 投票:0回答:2

如何对以下代码进行单元测试?

public Mono<MyObject> create(MyObject myobject)
{
    return Mono.fromCallable(() -> transactionTemplate.execute(status -> {
        try {
            return myRepository.save(myobject);
        }
        catch (Exception e) {
            log.error(e.getMessage());
            throw new ...;
        }

    })).subscribeOn(Schedulers.boundedElastic());
}

在我当前的测试中,我可以执行以下操作,但我也想模拟

myRepository.save()
并使用
Mockito.verify()
验证执行情况。

@Mock
private transient TransactionTemplate transactionTemplate;

@Test
void test() {
    when(transactionTemplate.execute(any())).thenReturn(myObject);
}
spring spring-boot spring-webflux project-reactor
2个回答
1
投票

对您的问题的一些评论:

  1. 为了测试 Mono/Flux 行为,建议使用 StepVerifier
  2. 如果你嘲笑transactionTemplate,那么嘲笑myRepository.save()是没有意义的
  3. myRepository.save() 的模拟在另一个测试中可能是有意义的,您将在其中测试实际 transactionTemplate.execute()
  4. 的正常工作

0
投票

在您的测试类中添加

@ContextConfiguration(classes = {
 ...,
 TransactionTemplateConfigration.class
 ...,
})
@MockBean({
 ...,
 PlatformTransactionManager.class
 ...,
}

这将使 TransactionTemplate 能够被注入,并且模拟

PlatformTransactionManager
将防止错误

© www.soinside.com 2019 - 2024. All rights reserved.