Java-如何测试捕获块?

时间:2018-06-23 16:36:21

标签: java unit-testing mockito try-catch catch-block

有点转贴,但是关于没有足够声誉的某些22捕捉意味着我无法对任何重复的线程发表评论! (咳嗽)

我正在尝试使用Mockito测试try-catch的catch块;是否有可能使模拟抛出由被测试方法处理的异常?我不能使用doThrow()... when()...或@Test(expected = Foo.class),因为已处理异常。我想测试该方法是否可以正确处理异常。

@Controller
public class StockExchangeController {

    public ModelAndView placeOrder(ModelAndView mav, MyObj myObj) {

        try {
            validator.validate(myObj); // Throws CustomException if validation fails
            mav.setViewName("successPage");

        } catch (CustomException ex) {
            mav.setViewName("failPage");
        }

        return mav;
    }
}

我希望能够对“ validatorObject”的行为进行存根,例如

doThrow(new CustomException()).when(validatorMock).validate();

有没有办法做到这一点?

答案here (Test catch block logic with Junit and mockito)不起作用(我相信),因为异常是在到达测试级别之前进行处理的。

提示和想法深表感谢!

2 个答案:

答案 0 :(得分:1)

BDD样式解决方案

Mockito 并不是处理异常的最佳解决方案,将 Mockito Catch-Exception

结合使用 Mockito + Catch-Exception + AssertJ
given(otherServiceMock.bar()).willThrow(new MyException());

when(myService).foo();

then(caughtException()).isInstanceOf(MyException.class);
样例代码 依存关系
  • eu.codearte.catch-exception:catch-exception:1.3.3
  • org.assertj:assertj-core:1.7.0
坏处
  • 仅支持不超过1.10.8的Mockito

答案 1 :(得分:1)

为什么doThrow(..).when(..)...不起作用?

placeOrder方法捕获异常并返回可测试的结果:

@RunWith(MockitoJUnitRunner.class)
public class TestStockExchangeController {

    @Mock
    Validator validator;

    @Mock MyObj myObj;

    @Test
    public void testException() throws CustomException {
        StockExchangeController sec = new StockExchangeController(validator);
        doThrow(new CustomException()).when(validator).validate(myObj);

        ModelAndView modelAndView = sec.placeOrder(new ModelAndView(), myObj);
        assertEquals("failPage", modelAndView.getViewName());
    }
}

我已经测试了这两个文件:

主要源代码:

//src/main/java/StockExchangeController.java
public class StockExchangeController {

    private ValidationFactory factory;

    public ModelAndView placeOrder(ModelAndView mav, MyObj myObj) {
        Validator validator = factory.getValidator("S");
        try {
            validator.validate(myObj); // Throws CustomException if validation fails
            mav.setViewName("successPage");
        } catch (CustomException ex) {
            mav.setViewName("failPage");
        }
        return mav;
    }
}

class CustomException extends Exception {}

interface ValidationFactory {
    Validator getValidator(String s);
}

class Validator {
    public void validate(MyObj myObj) throws CustomException {}
}

class ModelAndView {
    private String viewName;

    public void setViewName(String viewName) {
        this.viewName = viewName;
    }

    public String getViewName() {
        return viewName;
    }
}

class MyObj {}

测试源代码:

//src/test/java/TestStockExchangeController.java
//various imports
@RunWith(MockitoJUnitRunner.class)
public class TestStockExchangeController {

    @Mock
    private Validator validator;

    @Mock
    private ValidationFactory validationFactory;

    @InjectMocks
    StockExchangeController target = new StockExchangeController();

    @Test
    public void testException() throws CustomException {
        MyObj myObj = new MyObj();
        when(validationFactory.getValidator(anyString())).thenReturn(validator);
        doThrow(new CustomException()).when(validator).validate(myObj);

        ModelAndView modelAndView = target.placeOrder(new ModelAndView(), myObj);

        assertEquals("failPage", modelAndView.getViewName());
        verify(validator).validate(myObj);
    }
}