英文:
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<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());
}
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
- 对于测试Mono/Flux行为,建议使用StepVerifier。
- 如果你模拟transactionTemplate,那么模拟myRepository.save() 是没有意义的。
- 对myRepository.save() 的模拟可能在另一个测试中有意义,在那里你将测试实际transactionTemplate.execute() 的正确工作。
英文:
Some comments on your questions:
- For testing of Mono/Flux behavior it is recommended to use StepVerifier
- If you mock transactionTemplate, then mocking of myRepository.save() is meaningless
- The mocking of myRepository.save() could be meaningful in another test, where you will test the proper work of actual transactionTemplate.execute()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论