2013-05-17 72 views
5

例外が発生し、サーバーが500の内部サーバーエラーを返すと主張する必要があります。もちろんMockMVC同じテストケースで例外と応答コードをテストする方法

thrown.expect(NestedServletException.class); 
this.mockMvc.perform(post("/account") 
      .contentType(MediaType.APPLICATION_JSON) 
      .content(requestString)) 
      .andExpect(status().isInternalServerError()); 

を私はisInternalServerErrorまたはisOkを書く場合、それは問題ではdosen't:コードスニペットを提供する意思を強調するために

throw.exceptステートメントの下に例外がスローされても、テストは成功します。

どうすればこの問題を解決できますか?

答えて

3

あなたは以下のような何かを試すことができます -

  1. public class CustomExceptionMatcher extends 
    TypeSafeMatcher<CustomException> { 
    
    private String actual; 
    private String expected; 
    
    private CustomExceptionMatcher (String expected) { 
        this.expected = expected; 
    } 
    
    public static CustomExceptionMatcher assertSomeThing(String expected) { 
        return new CustomExceptionMatcher (expected); 
    } 
    
    @Override 
    protected boolean matchesSafely(CustomException exception) { 
        actual = exception.getSomeInformation(); 
        return actual.equals(expected); 
    } 
    
    @Override 
    public void describeTo(Description desc) { 
        desc.appendText("Actual =").appendValue(actual) 
         .appendText(" Expected =").appendValue(
           expected); 
    
    } 
    } 
    
  2. カスタム照合を作成し、以下のようにJUnitのクラスの@Ruleを宣言 -

    @Rule 
    public ExpectedException exception = ExpectedException.none(); 
    
  3. をカスタムを使用してくださいテストケースのmatcherとして -

    exception.expect(CustomException.class); 
    exception.expect(CustomException 
         .assertSomeThing("Some assertion text")); 
    this.mockMvc.perform(post("/account") 
        .contentType(MediaType.APPLICATION_JSON) 
        .content(requestString)) 
        .andExpect(status().isInternalServerError()); 
    

P.S:私はあなたの要件ごとにカスタマイズすることができ、一般的な擬似コードを提供してきました。

関連する問題