2014-02-07 126 views
2

我使用的是Spring MVC测试:在我的测试用例中,我传递了一个无效的Bar对象(年龄为零)。 MethodArgumentNotValidException正在抛出,但它嵌套在NestedServletException内。无论如何抛出MethodArgumentNotValidException异常从控制器通过现有/自定义HandlerExceptionResolver,以便我目前的测试案例checkHit2通过?在Junit测试用例中处理MethodArgumentNotValidException?

控制器:

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

    } 

的TestCase

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

结帐的'ExpectedException'规则,写自己的衍生物为您包装的异常? – 2014-02-07 06:45:53

+1

这意味着我弯曲我的测试用例来接受'NestedServletException'。我想要的是以某种方式改变控制器的行为,直接抛出'MethodArgumentNotValidException',而不是将它嵌套在'NestedServletException'中 – jacquard

回答

0

我有类似的问题,我固定它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")); 
}