代码之家  ›  专栏  ›  技术社区  ›  Anthony O.

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

  •  0
  • Anthony O.  · 技术社区  · 7 年前

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

    /* ... */ 参加我的考试吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Anthony O.    7 年前

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