1

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
  • Just write a function that does whatever you need and use that. Commented Aug 31, 2022 at 21:12

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That's what I end up doing too! I was wondering if there could be some other function I can "extend" but I agree this might be the cleanest way. Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.