2013-05-17 28 views
5

Tôi muốn khẳng định rằng một ngoại lệ được nâng lên và máy chủ trả về lỗi máy chủ nội bộ 500.MockMVC cách kiểm tra mã ngoại lệ và mã phản hồi trong cùng một trường hợp thử nghiệm

Để làm nổi bật mục đích một đoạn mã được cung cấp:

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

Tất nhiên nó doesnt vấn đề gì nếu tôi viết isInternalServerError hoặc isOk. Bài kiểm tra sẽ vượt qua bất kể nếu ngoại lệ được ném xuống dưới câu hỏi throw.except.

Bạn sẽ giải quyết vấn đề này bằng cách nào?

Trả lời

3

Bạn có thể thử một cái gì đó như dưới đây -

  1. Tạo một khớp tùy chỉnh

    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. Khai báo một @Rule trong lớp JUnit như dưới đây -

    @Rule 
    public ExpectedException exception = ExpectedException.none(); 
    
  3. Sử dụng Tuỳ chỉnh đối sánh trong trường hợp thử nghiệm là -

    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 .: tôi đã cung cấp một mã giả chung chung mà bạn có thể tùy chỉnh theo yêu cầu của bạn.

Các vấn đề liên quan