2012-10-20 1 views
7

나는 junit ExpectedExceptions' javadoc을 탐색 중이었고 그 예제에서 startsWith이 어디서 왔는지 (코드에 표시되어 있음) 이해할 수 없습니다. CoreMatcher utility class을 확인했지만 정적 startsWith 메서드를 찾을 수 없습니다.JUnit Matcher # startsWith의 선언은 어디에 있습니까?

해당 방법은 어디에 있습니까?

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?"); 
    } 
} 

답변

7

는 대부분의 경우 이것은 Hamcrest Matchers class에서 startsWith 방법입니다

는 (나는 분명히 나 자신을 작성할 수 있지만 요점은 그게 아니다).

3

ExpectedException에서 보면 두 개의 expectMessage 메소드가 정의되어 있습니다. 하나의 String과 하나의 Matcher가 실제로 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; 

모두

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

ExpectedException.none().expectMessage(startsWith("What")); //HERE 
수 있습니다