2012-10-20 92 views
7

我在瀏覽junit ExpectedExceptions' javadoc,我無法理解其示例中的startsWith來自哪裏(在代碼中標記爲HERE)。我檢查了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?"); 
    } 
} 

回答

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