12

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?

Jezzamon
  • 1,453
  • 1
  • 15
  • 27
  • 4
    Why not just convert the strings to lowercase and perform the assertion? – Ajmal Aug 13 '19 at 21:26
  • @AjmalAli Ah, that makes sense for a basic assertion. I realise I should specify that in my case I'm also using mockito so I need to supply a matcher. I'll update the question, but I guessing in my case I might just have to create a new matcher. – Jezzamon Aug 14 '19 at 04:24
  • 1
    Why don't you write your own ``Matcher``? Or use ``Matcher.matches(rexEx)``? – Tidder Aug 14 '19 at 05:27

3 Answers3

28

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));
lrn
  • 64,680
  • 7
  • 105
  • 121
Ajmal
  • 484
  • 1
  • 7
  • 14
  • Thanks for the answer! I realised I have an extra constraint that means I can't just use `string.contains` or convert to lowercase, so I updated the question – Jezzamon Aug 14 '19 at 04:30
  • 2
    That is not how RegExp flags are specified in Dart. You have to use `RegExp(r'your-substring', caseSensitive: false)` to make a regexp which ignores case. – lrn Aug 14 '19 at 08:30
4

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
  }
theCaptainXgod
  • 223
  • 1
  • 7
  • Sorry, not too obvious from the question title but I'm actually looking for a matcher that meets that criteria to use with mockito, not just an if statement – Jezzamon Oct 29 '20 at 21:51
  • 1
    A little bit late, but you for future readers: you can create Mockito matchers with arbitrary code using predicate: `Matcher containsSubstringNoCase(String substring) => predicate((String expected) => expected.toLowerCase().contains(substring.toLowerCase()));` – Luis Fernando Trivelatto Aug 26 '21 at 23:11
2

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