java - 在 Junit 测试用例中处理 MethodArgumentNotValidException?

标签 java spring spring-mvc-test

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

Controller :

@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>

最佳答案

我有类似的问题,我修复了它从 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"));
}

关于java - 在 Junit 测试用例中处理 MethodArgumentNotValidException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21620964/

相关文章:

Java 方法命名约定和重载

java - 在 Spring 中访问 MySQL 数据源 bean

java - 通过 spring 点燃缓存。动态驱逐期持续时间

java - Grails 与 REST 的 Spring 性能

java - @PreAuthorize 安全角色注解

java - 如何在单个布局中使用 RecyclerView 添加两个 Fragment 并滚动它们?

java - Android Studio 2.2.3 Base.Theme.AppCompat 错误

用于休息的 Spring MVC : How set a Locale value

java - Volley 解析错误 org.json.JSONException : End of input at character 0 of

java - Mockito when().thenReturn() 当它应该返回空列表时返回 Null