【问题标题】:Where is the declaration of JUnit Matcher#startsWith?JUnit Matcher#startsWith 的声明在哪里?
【发布时间】:2012-10-20 09:25:23
【问题描述】:

我正在浏览junit ExpectedExceptions' javadoc,但我不明白他们示例中的startsWith 来自哪里(在代码中标记为此处)。我检查了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?");
    }
}

【问题讨论】:

    标签: java junit hamcrest


    【解决方案1】:
    import static org.hamcrest.core.StringStartsWith.startsWith;
    

    同时启用

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

    ExpectedException.none().expectMessage(startsWith("What")); //HERE
    

    【讨论】:

      【解决方案2】:

      这很可能是 Hamcrest org.hamcrest.Matchers class 中的 startsWith 方法。

      【讨论】:

        【解决方案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));
        }
        

        【讨论】:

          猜你喜欢
          • 2015-03-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多