0

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!

cxc
  • 201
  • 2
  • 10

1 Answers1

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.

Ben Hoyt
  • 10,694
  • 5
  • 60
  • 84
  • 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! – cxc Sep 01 '22 at 15:22