9

我正在浏览junitExpectedExceptions的 javadoc,但我无法理解startsWith他们示例中的 来自哪里(在代码中标记为 HERE)。我检查了CoreMatcher实用程序类,但找不到任何静态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?");
    }
}
4

3 回答 3

10
import static org.hamcrest.core.StringStartsWith.startsWith;

使两者

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

ExpectedException.none().expectMessage(startsWith("What")); //HERE
于 2014-02-17T06:38:17.230 回答
8

这很可能是startsWith来自 Hamcrestorg.hamcrest.Matchers的方法。

于 2012-10-20T09:55:34.227 回答
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));
}
于 2012-10-20T16:29:28.113 回答