2012-10-20 49 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