有点转发,但是关于没有足够的声誉的某些 catch-22 意味着我无法评论任何重复的线程!(咳咳)
我正在尝试使用 Mockito 测试尝试捕获的捕获块;是否可以使模拟抛出由正在测试的方法处理的异常?我不能使用 doThrow()...当()...或 @Test(预期 = 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;
}
}
我希望能够存根我的“验证器对象”的行为,例如
doThrow(new CustomException()).when(validatorMock).validate();
有办法做到这一点吗?
这里的答案(使用Junit和mockito测试捕获块逻辑)不起作用(我相信),因为异常是在到达测试级别之前处理的。
非常感谢提示和想法!
BDD型解决方案
单独使用Mockito不是处理异常的最佳解决方案,请将Mockito与Catch-Exception一起使用
given(otherServiceMock.bar()).willThrow(new MyException());
when(myService).foo();
then(caughtException()).isInstanceOf(MyException.class);
为什么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);
}
}