2012-10-20 36 views
7

Tôi đang duyệt số junit ExpectedExceptions' javadoc và tôi không thể hiểu được nơi startsWith trong ví dụ của họ đến từ (được đánh dấu ở đây trong mã). Tôi đã kiểm tra CoreMatcher utility class nhưng không thể tìm thấy bất kỳ phương pháp tĩnh startsWith nào.Tuyên bố của JUnit Matcher # startsWith ở đâu?

Phương pháp đó nằm ở đâu?

(Tôi rõ ràng là có thể viết nó bản thân mình nhưng đó không phải là điểm)

public static class HasExpectedException { 
    @Rule 
    public ExpectedException thrown = ExpectedException.none(); 

    @Test 
    public void throwsNullPointerExceptionWithMessage() { 
     thrown.expect(NullPointerException.class); 
     thrown.expectMessage("happened?"); 
     thrown.expectMessage(startsWith("What")); //HERE 
     throw new NullPointerException("What happened?"); 
    } 
} 

Trả lời

7

Nhiều khả năng đây là phương pháp startsWith từ hamcrest Matchers class.

3

Nhìn vào ExpectedException, chúng ta có thể thấy rằng có hai phương thức expectMessage được xác định, một String và một Matcher, thực sự là org.hamcrest.Matcher.

/** 
* Adds to the list of requirements for any thrown exception that it should 
* <em>contain</em> string {@code substring} 
*/ 
public void expectMessage(String substring) { 
    expectMessage(containsString(substring)); 
} 

/** 
* Adds {@code matcher} to the list of requirements for the message returned 
* from any thrown exception. 
*/ 
public void expectMessage(Matcher<String> matcher) { 
    expect(hasMessage(matcher)); 
} 
5
import static org.hamcrest.core.StringStartsWith.startsWith; 

cho phép cả hai

assertThat(msg, startsWith ("what")); 

ExpectedException.none().expectMessage(startsWith("What")); //HERE