How to compare case insensitive string using FluentAssertions? C# [duplicate]
Asked Answered
A

1

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.

Accentuate answered 28/12, 2017 at 9:59 Comment(2)
Why don't you just call .ToLower() on the string you're comparing against?Brasca
@Brasca looking for a better way. Note that when you use ToLower() and it fails, FluentAssertions will raport changed values (lowercased).Accentuate
W
14

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.

Whidah answered 28/12, 2017 at 10:2 Comment(4)
It is nice but, as I added in the question it will fail for Turkich culture.Accentuate
Then use the duplicate questions accepted answer. symbol.Should().Equal(expectedSymbol, (o1, o2) => string.Compare(o1, o2, StringComparison.InvariantCultureIgnoreCase))Whidah
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.Pyxidium
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 github.com/fluentassertions/fluentassertions/issues/…Pyxidium

© 2022 - 2024 — McMap. All rights reserved.