JUnit Matcher的声明在哪里#startingWith?

时间:2012-10-20 09:25:23

标签: java junit hamcrest

我正在浏览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?");
    }
}

3 个答案:

答案 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));
}