6

How can I easy compare string case insensitive using FluentAssertions?

Something like:

symbol.Should().Be(expectedSymbol, StringComparison.InvariantCultureIgnoreCase);

Edit: Regarding possible duplicate and code: symbol.Should().BeEquivalentTo(expectedSymbol);

it is comparing using CurrentCulture. And it will brake in situation like Turkish culture. Where Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR", false); string upper = "in".ToUpper(); // upper == "İN" "in".Should().BeEquivalentTo("In"); // It will fail

so the part "StringComparison.InvariantCultureIgnoreCase" is crucial here.

Krzysztof Morcinek
  • 1,011
  • 13
  • 42

1 Answers1

12

You can use

symbol.ToLower().Should().Be(expectedSymbol.ToLower());

OR

Instead of Be use BeEquivalentTo

symbol.Should().BeEquivalentTo(expectedSymbol);

BeEquivalentTo metadata states

Asserts that a string is exactly the same as another string, including any leading or trailing whitespace, with the exception of the casing.

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • It is nice but, as I added in the question it will fail for Turkich culture. – Krzysztof Morcinek Dec 28 '17 at 11:49
  • 1
    Then use the duplicate questions accepted answer. `symbol.Should().Equal(expectedSymbol, (o1, o2) => string.Compare(o1, o2, StringComparison.InvariantCultureIgnoreCase))` – Nikhil Agrawal Dec 28 '17 at 11:52
  • ToLower or ToUpper should almost never be included as part of a string comparison solution. It will fail for many languages. Plus it performs slower because it iterates over the string multiple times and increases heap allocation. I hope no one copies that into their code without first thinking about the consequences. – Lee Grissom Jan 23 '23 at 22:30
  • Btw, this comment found in Github regarding FAv7 from Dec-18-2022: `...we then replace the BeEquivalentTo on string with Be and an overload of Be that takes a StringComparison` https://github.com/fluentassertions/fluentassertions/issues/2064#issuecomment-1356734362 – Lee Grissom Jan 23 '23 at 22:32