jUnit中的AssertContains对字符串进行断言

251

有没有更好的方法来编写jUnit测试用例?

String x = "foo bar";
Assert.assertTrue(x.contains("foo"));

11
我认为这已经很不错了,建议的选项可读性较差。 - The Godfather
10
@TheGodfather,虽然不太易读,但会产生更有意义的断言错误(例如,接受的响应将显示字符串的差异,而OP的解决方案在失败时只会显示“False when expected True”)。 - Mike
1
一个断言之所以“更好”,是因为它在失败时提供了更好的错误信息。它在代码中的可读性次于此,因为你只有在它失败时才需要查看代码,而失败消息是你首先看到的东西。 - rjmunro
问题本身应该是被接受的答案:D - d1Master
@rjmunro 你可以将自己的信息作为 assertTrue 的参数 传递,例如 Assert.assertTrue("应该包含子字符串 'foo'", x.contains("foo")); - rook218
12个回答

0
如果您能够并愿意添加外部库,则前面的答案相当不错。由于各种原因,这可能并非如此。如果您不能/不想向项目添加另一个依赖项,或者只是想将hamcrest保持在一定距离之内,那么您可以使用随JUnit一起提供的hamcrest部分。
例如,org.hamcrest.BaseMatcher和org.hamcrest.Matcher随JUnit 4.10一起提供。其中一个实现可能是:
public class StringMatchers {
    public static Matcher<String> contains(String expected) {
        return new BaseMatcher<String>() {
            @Override
            public boolean matches(Object actual) {
                String act = (String) actual;
                
                return act.contains(expected);
            }

            @Override
            public void describeTo(Description desc) {
                desc.appendText("should contain ").appendValue(expected);
            }
        };
    }
}

然后,您可以使用import static <package>.StringMatchers.contains将其导入其他测试文件。这将使您得到以下语句:

assertThat(x, contains(y));

附注:这与其他库非常相似,因此如果它们实现得非常不同,我会感到惊讶。

源代码:https://programmingideaswithjake.wordpress.com/2014/11/08/advanced-creation-of-hamcrest-matchers/ **并非所有内容都有效!


0

我在这个页面上尝试了许多答案,但都没有真正起作用:

  • org.hamcrest.CoreMatchers.containsString 无法编译,无法解决方法。
  • JUnitMatchers.containsString 已过时(并引用了 CoreMatchers.containsString)。
  • org.hamcrest.Matchers.containsString:NoSuchMethodError

所以,我决定使用问题中提到的简单而可行的方法,而不是编写可读性强的代码。

希望能出现另一种解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接