How do I unit test a method that uses TransactionTemplate.execute and verify the code executed inside execute()

huangapple go评论53阅读模式
英文:

How do I unit test a method that uses TransactionTemplate.execute and verify the code executed inside execute()

问题

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

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);
}
英文:

How do I unit test the below code?

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

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

In my current test I can do the following below, but I also want to mock the myRepository.save() and verify execution with Mockito.verify().

@Mock
private transient TransactionTemplate transactionTemplate;

@Test
void test() {
    when(transactionTemplate.execute(any())).thenReturn(myObject);
}

答案1

得分: 1

  1. 对于测试Mono/Flux行为,建议使用StepVerifier
  2. 如果你模拟transactionTemplate,那么模拟myRepository.save() 是没有意义的。
  3. myRepository.save() 的模拟可能在另一个测试中有意义,在那里你将测试实际transactionTemplate.execute() 的正确工作。
英文:

Some comments on your questions:

  1. For testing of Mono/Flux behavior it is recommended to use StepVerifier
  2. If you mock transactionTemplate, then mocking of myRepository.save() is meaningless
  3. The mocking of myRepository.save() could be meaningful in another test, where you will test the proper work of actual transactionTemplate.execute()

huangapple
  • 本文由 发表于 2023年5月28日 17:19:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76350777.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定