How can make a matcher for a string containing a substring, while ignoring case

11.9k views Asked by At

I'm writing a unit test using mockito to mock a dependency and check we're calling it with the right argument. We should be passing in a string, so I'm trying to match on that function argument, but without asserting on the whole string, in case we change the wording. So I want to match on just one word in the message, but that word could be at the start of the sentence or in the middle, so it might start with a capital.

The dart matchers have equalsIgnoringCase, and contains, but I can't find any matcher that handles both, something like containsIgnoringCase. Is there any way to check for the substring, while also ignoring case in a matcher?

3

There are 3 answers

0
Luis Fernando Trivelatto On BEST ANSWER

Since the OP updated the question with the constraint that it should be a Matcher (for mockito):

It's possible to create Matchers with arbitrary code using predicate. In this case, using Ajmal's answer:

Matcher containsSubstringNoCase(String substring) =>
  predicate((String expected) => expected.contains(RegExp(substring, caseSensitive: false)));

Then:

expect('Foo', containsSubstringNoCase('foo'));  // true
2
Ajmal On

You can pass in a regex to the contains method with the caseSensitive property set to false.

string.contains(new RegExp(r'your-substring', caseSensitive: false));
2
theCaptainXgod On

Easiest Way? This is how I did in DART but I believe it will be applicable for all languages.

 if (string1.toLowerCase().contains(string2.toLowerCase())) {
    //TODO: DO SOMETHING
  }