2014-02-07 127 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")); 
}