我正在浏览junit ExpectedExceptions
' javadoc,我无法理解他们示例中startsWith
的来源(在代码中标记为HERE)。我检查了CoreMatcher
utility class,但找不到任何静态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?");
}
}
答案 0 :(得分:9)
import static org.hamcrest.core.StringStartsWith.startsWith;
启用两者
assertThat(msg, startsWith ("what"));
和
ExpectedException.none().expectMessage(startsWith("What")); //HERE
答案 1 :(得分:7)
这很可能是Hamcrest Matchers class中的startsWith方法。
答案 2 :(得分: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));
}