【问题标题】:Assertion fail message for string contains substring [duplicate]字符串的断言失败消息包含子字符串[重复]
【发布时间】:2013-03-29 20:48:15
【问题描述】:

我最近对文本生成软件的文本输出做了很多功能测试,发现自己写了很多

assertTrue(actualString.contains(wantedString));

但是,失败时的消息是非描述性的,例如

Expected [true], but was [false]

另一种方法是包含自定义失败消息

String failMsg = String.format("Wanted string to contain: %s, Actual string: %s", wantedString, actualString);
assertTrue(failMsg, actualString.contains(wantedString));

但一直手动执行此操作感觉有点乏味。 有没有更好的办法?

【问题讨论】:

  • 就我个人而言,我大部分时间都不会写额外的消息 - 测试很少失败,当它们失败时,调试它们以获取更多详细信息:)
  • 对于单元测试 - 不,但这些是功能(集成)测试,可能在某处的 Jenkins 服务器上运行,增加的详细程度很有帮助。

标签: java string junit functional-testing assertions


【解决方案1】:

使用 hamcrest Matcher containsString()

// Hamcrest assertion
assertThat(person.getName(), containsString("myName"));

// Error Message
java.lang.AssertionError:
Expected: a string containing "myName"
     got: "some other name"

您可以选择添加更详细的错误消息。

// Hamcrest assertion with custom error message
assertThat("my error message", person.getName(), containsString("myName"));

// Error Message
java.lang.AssertionError: my error message
Expected: a string containing "myName"
     got: "some other name"

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 2019-03-15
    • 2020-08-26
    • 1970-01-01
    相关资源
    最近更新 更多