字符串的断言失败消息包含子字符串 [英] Assertion fail message for string contains substring

查看:703
本文介绍了字符串的断言失败消息包含子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have done a lot of functional testing on text outputs on text generating software lately, an find myself writing a lot of

assertTrue(actualString.contains(wantedString));

然而,此失败的消息是非描述性的,如

However, the message for when this fails is something non-descriptive like

Expected [true], but was [false]

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

An alternative is to include a custom fail message as

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

但是一直手动执行此操作会感觉有点乏味。
还有更好的方法吗?

But it feels a bit tedious to do this manually all the time. Is there a better way?

推荐答案

使用hamcrest Matcher containsString()

Use hamcrest Matcher containsString()

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

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

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

You can optional add an even more detail error message.

// 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"

这篇关于字符串的断言失败消息包含子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆