I have a method which takes a StringComparison argument, and it really needs a unit test to prove it is performing the right comparison type.
This is basically what I have so far. It differentiates Ordinal from the rest by comparing "oe" and "œ" (see System.String). I haven't, however, found a way to differentiate CurrentCulture from InvariantCulture.
using System;
using NUnit.Framework;
using System.Threading;
using System.Globalization;
namespace NUnitTests
{
[TestFixture]
public class IndexOfTests
{
[Test]
public void IndexOf_uses_specified_comparison_type()
{
StringComparison comparisonTypePerformed;
result = TestComparisonType(StringComparison.CurrentCulture);
Assert.AreEqual(StringComparison.CurrentCulture, comparisonTypePerformed);
result = TestComparisonType(StringComparison.InvariantCulture);
Assert.AreEqual(StringComparison.CurrentCulture, comparisonTypePerformed);
result = TestComparisonType(StringComparison.Ordinal);
Assert.AreEqual(StringComparison.CurrentCulture, comparisonTypePerformed);
}
bool TestComparisonType(StringComparison comparisonType)
{
int result;
// Ensure the current culture is consistent for test
var prevCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false);
try
{
result = IndexOf("oe", "œ", comparisonType);
if (result == 0)
{
// The comparison type performed was either CurrentCulture,
// InvariantCulture, or one of the case-insensitive variants.
// TODO: Add test to differentiate between CurrentCulture and InvariantCulture
throw new NotImplementedException();
result = IndexOf("???????", "???????", StringComparison.CurrentCulture);
//...
}
else // result == -1
{
// The comparison type performed was either Ordinal or OrdinalIgnoreCase
result = IndexOf("a", "A", StringComparison.CurrentCulture);
if (result)
Console.WriteLine("Comparison type was OrdinalIgnoreCase");
else
Console.WriteLine("Comparison type was Ordinal");
}
}
finally
{
Thread.CurrentThread.CurrentCulture = prevCulture;
}
}
}
}
I considered using the Turkish problem by comparing "i" and "I", but it only works for case-insensitive comparisons.
I've looked around and couldn't find a case where InvariantCulture differs from other cultures in a string equality test (only sort order and parsing/serialization). For example, depending on the culture, "ô" and "o" will sort differently, but all cultures return the same result in equality tests.
Is there an equality test to differentiate InvariantCulture from any other culture?
EDIT: The german "ß" and "ss" give the same result for all cultures so they won't work.
EDIT: Really, all that is needed is two strings considered equal in one culture, and unequal in another.