Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 368
Jezzamon Avatar asked Aug 13 '19 21:08

Jezzamon


People also ask

How do you compare strings to ignore cases?

The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences. This method returns true if the strings are equal, and false if not. Tip: Use the compareToIgnoreCase() method to compare two strings lexicographically, ignoring case differences.

How do you match a substring to a string?

Simple Approach: The idea is to run a loop from start to end and for every index in the given string check whether the sub-string can be formed from that index.

Does == ignore case?

Java String: equalsIgnoreCase() MethodTwo strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case.


3 Answers

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));
like image 168
Ajmal Avatar answered Nov 24 '22 05:11

Ajmal


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
  }
like image 26
theCaptainXgod Avatar answered Nov 24 '22 07:11

theCaptainXgod


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
like image 22
Luis Fernando Trivelatto Avatar answered Nov 24 '22 06:11

Luis Fernando Trivelatto