Spring boot 在@Spy上调用原始方法,然后引发异常

Spring boot 在@Spy上调用原始方法,然后引发异常,spring-boot,mockito,spring-test,spring-boot-test,Spring Boot,Mockito,Spring Test,Spring Boot Test,我有一个@Transactional方法,当事务在调用后失败时,我必须测试该方法,例如: @服务 公共类MyService{ @交易的 公共方法(){ //[…]我必须在测试中运行一些代码,并在调用异常之后但提交事务之前抛出异常,以便回滚事务 } } 以下是测试类: @RunWith(SpringRunner.class) @SpringBootTest(类=MyApp.class) 公共类MyServiceTest{ @间谍 私人MyService-MyService; @试验 公共void

我有一个
@Transactional
方法,当事务在调用后失败时,我必须测试该方法,例如:

@服务
公共类MyService{
@交易的
公共方法(){
//[…]我必须在测试中运行一些代码,并在调用异常之后但提交事务之前抛出异常,以便回滚事务
}
}
以下是测试类:

@RunWith(SpringRunner.class)
@SpringBootTest(类=MyApp.class)
公共类MyServiceTest{
@间谍
私人MyService-MyService;
@试验
公共void testMyMethod(){
doAnswer(/*一些调用real方法的代码,然后抛出异常以取消事务*/)
.when(myService.myMethod();
//[…]当服务在事务中失败但其实际方法已正确执行后测试其他服务的其他代码
}
}

你能告诉我在
/**/我测试中的一部分?

您只需使用
调用.callRealMethod()
然后
doAnswer
中抛出一些异常:

@Test
public void testMyMethod() {
    doAnswer(invocation -> {
        invocation.callRealMethod();
        throw new IllegalStateException();
    })
    .when(myService).myMethod();
    // [...] other code that test other services when that service failed in the transaction but after its real method has been correctly executed
}