3

私はSpring MVCテストを使用しています:私のテストケースでは、無効なBarオブジェクト(age with zero)を渡しています。MethodArgumentNotValidExceptionがスローされていますが、 内にネストされていますNestedServletException。私の現在のテストケースが合格するようにMethodArgumentNotValidException、コントローラーから既存/カスタムを介して例外をスローする方法はありますか?HandlerExceptionResolvercheckHit2

コントローラ:

@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;
    }
...
}

ジャント出力

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

1 に答える 1

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"));
}
于 2015-05-08T11:36:57.557 に答える