英文:
Function like assert.Contains by stretchr/testify but ignore case and whitespace
问题
例如,我有这个测试代码:
assert.Contains(t, "HELLO WORLD", "hello world")
我希望这个测试返回 true。显然,我可以在测试之前使用 strings.TrimSpace()
、strings.ReplaceAll()
和 strings.ToLower()
来清理字符串。但是当我有几十个这样的测试时,这样做会变得很繁琐。有没有更简洁的方法来实现这个?或者我是否可以修改或创建一个自定义的 assert.NormalizedContains()
?谢谢你的建议!
英文:
For example, I have this test here
assert.Contains(t, "HELLO WORLD", "hello world)
and I want this to return true. Obviously, I can clean up the string with strings.TrimSpace()
, strings.ReplaceAll()
, and strings.ToLower()
beforehand. Although it gets cumbersome when I have dozens of these. Is there any cleaner way to achieve this? Or can I possibly modify or create a customized assert.NormalizedContains()
? Thank you for the input!
答案1
得分: 0
你可以创建一个名为 normalize
的函数,其参数为字符串类型,返回值也是字符串类型,并将其与 assert.Contains
一起使用,例如:
func normalize(s string) string {
return strings.ToLower(strings.Join(strings.Fields(s), ""))
}
func TestFoo(t *testing.T) {
assert.Contains(t, normalize("HELLO WORLD"), "hello world")
// 或者你可能想要同时规范化两个字符串:
assert.Contains(t, normalize("HELLO WORLD"), normalize("hello world"))
}
如果你确实经常这样做,你可以创建一个自定义的 assertNormalizedContains
函数,其参数为 t *testing.T
、haystack
和 needle
两个字符串,并在使用时替代 assert.Contains
。不过我认为这样做可能不够清晰。
英文:
You could create a func normalize(s string) string
and use that together with assert.Contains
, for example:
func normalize(s string) string {
return strings.ToLower(strings.Join(strings.Fields(s), ""))
}
func TestFoo(t *testing.T) {
assert.Contains(t, normalize("HELLO WORLD"), "hello world")
// or you might want to normalize both:
assert.Contains(t, normalize("HELLO WORLD"), normalize("hello world"))
}
If you're really doing this a lot, you could create a custom func assertNormalizedContains(t *testing.T, haystack, needle string)
and just use that instead of assert.Contains
. Though I'd argue that's not as clear.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论