Google Test - Test that a string does not contain a string
Asked Answered
S

1

21

Using Google Test, I need a way to verify that a string that was returned by my class under test does not contain a particular string. I can currently test that a string does contain another string by using EXPECT_THAT and MatchesRegex; however, I don't know how to build a valid POSIX Extended regular expression for not containing a word, and I don't know how to negate a MatchesRegex call.

I tried doing a regex I found here on SO:

EXPECT_THAT(returnedString, MatchesRegex("^(?!.*badword).*$"));

but that gives me an error:

Regular expression "^(?!.*badword).*$" is not a valid POSIX Extended regular expression.

Any other suggestions on how I could do this?

Sanctified answered 14/1, 2016 at 22:49 Comment(0)
R
36

You can combine matchers HasSubstr and Not so your code would look like:

EXPECT_THAT(returnedString, Not(HasSubstr("badword")));

Check Google Mock documentation for matchers for full reference.

Refurbish answered 15/1, 2016 at 7:35 Comment(2)
It seems we also need using ::testing::HasSubstr; for this to work. ThanksNigrescent
Updated link: github.com/google/googletest/blob/master/docs/…Gracielagracile

© 2022 - 2024 — McMap. All rights reserved.