【发布时间】:2011-04-24 05:52:17
【问题描述】:
我有一个采用 StringComparison 参数的方法,它确实需要一个单元测试来证明它正在执行正确的比较类型。
这基本上是我目前所拥有的。它通过比较“oe”和“œ”来区分 Ordinal(参见System.String)。但是,我还没有找到区分 CurrentCulture 和 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”和“I”来使用土耳其语问题,但它仅适用于不区分大小写的比较。
我环顾四周,在字符串相等性测试(仅排序顺序和解析/序列化)中找不到 InvariantCulture 与其他文化不同的情况。例如,根据文化,“ô”和“o”的排序方式不同,但所有文化在相等性测试中返回相同的结果。
是否有用于区分 InvariantCulture 与任何其他文化的平等测试?
编辑: 德语“ß”和“ss”对所有文化都给出相同的结果,因此它们不起作用。
编辑: 实际上,只需要两个字符串在一种文化中相等,而在另一种文化中不相等。
【问题讨论】:
标签: c# unit-testing culture