【问题标题】:Call original method on a @Spy then throw an exception在 @Spy 上调用原始方法然后抛出异常
【发布时间】:2019-03-22 00:29:29
【问题描述】:

我有一个@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
    }
}

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

【问题讨论】:

    标签: spring-boot mockito spring-test spring-boot-test


    【解决方案1】:

    您可以简单地使用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
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-27
      • 2012-11-22
      • 2019-07-28
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      • 2016-07-10
      相关资源
      最近更新 更多