Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive comparison in Contains under nUnit

I'm trying to assert that a list contains a certain string. Since I'd need the condition to be evaluated case insensitively, I used a workaround (something along this blog post).

However, I'd like to know why there seems not to be a way to make the Assert.Contains method perform the comparison without regard of case sensitivity. Or is there a way to do that? (When I googled it, I only got hits on constraints for the Assert.That method on the official page for nUnit.)

like image 610
Konrad Viltersten Avatar asked Jul 08 '14 14:07

Konrad Viltersten


People also ask

Is contains case-sensitive in C#?

Contains() method in C# is case sensitive. And there is not StringComparison parameter available similar to Equals() method, which helps to compare case insensitive.

How do you do case insensitive string comparison?

The most basic way to do case insensitive string comparison in JavaScript is using either the toLowerCase() or toUpperCase() method to make sure both strings are either all lowercase or all uppercase.

What is case insensitive in C#?

Case insensitive containsIndexOf() finds the first occurrence of a particular string inside another string. The comparison type is determined by the StringComparison parameter, which we pass as the second parameter. String. IndexOf() returns the position of the first occurrence of a substring inside a string.

Is JavaScript match case insensitive?

Case-insensitive: It means the text or typed input that is not sensitive to capitalization of letters, like “Geeks” and “GEEKS” must be treated as same in case-insensitive search. In Javascript, we use string. match() function to search a regexp in a string and match() function returns the matches, as an Array object.


2 Answers

There is no way to specify ignoreCase in the Assert.Contains. Whether it's something that is overlooked or intended I do not know. You can, however, use

StringAssert.AreEqualIgnoringCase(left, right);

in your unit tests to achieve the same results.

Alternatively, if you wish to stick with the Assert.Foo() "theme", you could do something like this:

Assert.IsTrue(string.Equals(left, right, StringComparison.OrdinalIgnoreCase));

or, since Contains treats arrays:

Assert.IsTrue(list.Any(element => element.ToUpper() == "VILTERSTEN"));

where you call ToUpper() on both the left and right string operands, which effectively makes the comparison ignore case as well. OrdinalIgnoreCase is to ensure some corner cases (read: Turkish) of cultures do not cause unexpected results. If you are interested in reading up on that, have a look at the Turkey test.

like image 89
aevitas Avatar answered Sep 16 '22 15:09

aevitas


In NUnit 3, the following syntax can be used:

Assert.That(new[] {"red", "green", "blue"}, Does.Contain("RED").IgnoreCase);
like image 38
Nikolay Hidalgo Diaz Avatar answered Sep 18 '22 15:09

Nikolay Hidalgo Diaz