在@Spy上调用原始方法,然后提出异常



我有一个@Transactional方法,我必须测试交易何时被调用后,例如:

@Service
public class MyService {
    @Transactional
    public void myMethod() {
        // [...] some code I must run in my test, and throw an exception after it has been called but before the transaction is commited in order for the transaction to be rolled back
    }
}

这是测试类:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApp.class)
public class MyServiceTest {
    @SpyBean
    private MyService myService;
    @Test
    public void testMyMethod() {
        doAnswer(/* some code which would call the real method, then throw an exception in order to cancel the transaction */)
        .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
    }
}

您能告诉我我的测试中要放入/* ... */部分的代码吗?

您可以简单地使用invocation.callRealMethod(),然后throw 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
}

相关内容

  • 没有找到相关文章

最新更新