目的方法

public void foo(){
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    boolean success = transactionTemplate.execute(new TransactionCallback<Boolean>() {
        @Override
        public Boolean doInTransaction(TransactionStatus status) {
            try {
                barService.bar();
                return true;
            } catch (ApiException e) {
                System.out.println("call bar failed");
                e.printStackTrace();
                status.setRollbackOnly();
            }
            return false;
        }
    });
    if(success){
        barService.doSomething();
    }else{
        barService.doSomethingElse();
    }
}

测试方法

@Test
public void test_foo_call_bar_failed(){
    Mockito.doThrow(new ApiException("100000","Test")).when(barService).bar(); // 模拟调用bar方法抛出异常
 
    service.foo();
 
    Mockito.verify(barService).bar();
    Mockito.verify(barService).doSomethingElse(); // 表示执行了doSomethingElse方法
    Mockito.verify(barService,Mockito.times(0)).doSomething();
}

但是实际执行上面的测试用例 报错

java.lang.NullPointerException
    at com.foobar.service.FooService.foo(FooService.java:68)

似乎匿名内部类不能这样简答处理
修改测试方法

@Test
public void test_foo_call_bar_failed(){
    when(transactionTemplate.execute(Mockito.any(TransactionCallback.class))).thenAnswer(new Answer(){
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            TransactionCallback arg = (TransactionCallback)args[0];
            return arg.doInTransaction(new SimpleTransactionStatus());
        }
    });
    Mockito.doThrow(new ApiException("100000","Test")).when(barService).bar();
 
    service.foo();
 
    Mockito.verify(barService).bar();
    Mockito.verify(barService).doSomethingElse();
    Mockito.verify(barService,Mockito.times(0)).doSomething();
}

这时就能测试通过了。

参考文档
http://stackoverflow.com/ques...


zhuguowei2
825 声望26 粉丝

引用和评论

0 条评论