【问题标题】:Handling MethodArgumentNotValidException in Junit testcase?在 Junit 测试用例中处理 MethodArgumentNotValidException?
【发布时间】:2014-03-04 11:08:44
【问题描述】:

我正在使用 Spring MVC 测试:在我的测试用例中,我传递了一个无效的 Bar 对象(年龄为零)。 MethodArgumentNotValidException 被抛出,但它嵌套在 NestedServletException 中。有没有办法通过现有/自定义的HandlerExceptionResolver 从控制器抛出MethodArgumentNotValidException 异常,以便我当前的测试用例checkHit2 通过?

控制器:

@RequestMapping(value="/test", method = RequestMethod.POST, headers="Accept=application/json")
    @ResponseBody
    public Bar getTables(@Valid @RequestBody Bar id) {
        return id;

    }

测试用例

@Before
public void setUp() {

    mockMvc =  standaloneSetup(excelFileUploader).setHandlerExceptionResolvers(new SimpleMappingExceptionResolver()).build();
}

@Test(expected=MethodArgumentNotValidException.class)
    public void checkHit2() throws Exception {
        Bar b = new Bar(0, "Sfd");
        mockMvc.perform(
                post("/excel/tablesDetail").contentType(
                        MediaType.APPLICATION_JSON).content(
                        TestUtil.convertObjectToJsonBytes(b)));

条形

public class Bar {

    @JsonProperty("age")
    @Min(value =1)
    private int age;
public Bar(int age, String name) {
        super();
        this.age = age;
        this.name = name;
    }
...
}

Junit 输出

java.lang.Exception: Unexpected exception, 
expected<org.springframework.web.bind.MethodArgumentNotValidException> but 
was<org.springframework.web.util.NestedServletException>

【问题讨论】:

  • 检查ExpectedException 规则并为您的包装异常编写您自己的衍生产品?
  • 这意味着我正在弯曲我的测试用例以接受NestedServletException。我想要的是以某种方式更改控制器行为以直接抛出 MethodArgumentNotValidException 而不是将其嵌套在 NestedServletException

标签: java spring spring-mvc-test


【解决方案1】:

我遇到了类似的问题,我修复了它,从 NestedServletException 扩展了我的异常类。例如:

@RequestMapping(value = "/updateForm/{roleID}", method = RequestMethod.GET)
   public String updateForm(@PathVariable Long roleID, Model model, HttpSession session) throws ElementNotFoundException {

  Role role = roleService.findOne(roleID);
  if (role == null) {
     throw new ElementNotFoundException("Role");
  }

  ...
}

我的异常看起来像:

public class ElementNotFoundException extends NestedServletException {

   private static final long serialVersionUID = 2689075086409560459L;

   private String typeElement;

   public ElementNotFoundException(String typeElement) {
     super(typeElement);
     this.typeElement = typeElement;
   }

   public String getTypeElement() {
     return typeElement;
   }

}

所以我的测试是:

@Test(expected = ElementNotFoundException.class)
public void updateForm_elementNotFound_Test() throws Exception {
  String roleID = "1";

  Mockito.when(roleService.findOne(Long.valueOf(roleID))).thenReturn(null);

  mockMvc.perform(get("/role/updateForm/" + roleID)).andExpect(status().isOk()).andExpect(view().name("exception/elementNotFound"));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 2015-01-19
    • 1970-01-01
    相关资源
    最近更新 更多