Can Fluent Assertions对IEnumerable 使用字符串不敏感的比较?

我有一对列表,我试图使用Fluent断言进行比较。 我可以轻松编写比较代码,但我想使用Fluent Assertions,以便我可以在测试失败消息中显示出来的原因。

到目前为止我看到的所有东西似乎都使用默认的Object.Equals比较,它区分大小写。 我似乎无法将IComparer传递给Equal或Contains方法,那么还有其他方法吗?

[TestMethod()] public void foo() { var actual = new List { "ONE", "TWO", "THREE", "FOUR" }; var expected = new List { "One", "Two", "Three", "Four" }; actual.Should().Equal(expected); } 

我们可以在Equal()方法中添加一个可选的lambda表达式。 然后,你可以做类似的事情

 [TestMethod()] public void foo() { var actual = new List { "ONE", "TWO", "THREE", "FOUR" }; var expected = new List { "One", "Two", "Three", "Four" }; actual.Should().Equal(expected, (o1, o2) => string.Compare(o1, o2, StringComparison.InvariantCultureIgnoreCase)) } 

IComparer也是可能的,但我认为Equal()默认行为的偶然exception不能保证额外的自定义编写类。 实际上,单独的IComparer可能会模糊测试的意图。 让我知道你们认为什么是最好的解决方案,所以我可以在Codeplex 1.8.0版本上添加它作为一个问题。

在FluentAssetrions的更高版本中,可以使用以下内容:

 stringValue.Should().BeEquivalentTo(stringToCompare); 

[元数据]摘要:

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

适用于我使用的版本(FluentAssertions.2.2.0.0)。

如何通过扩展方法(或两个)添加新的Fluent断言? 我编写了代码,将.EqualInsensitively(...)添加到字符串集合的可用流畅断言中。

我已经把代码放在外部的pastebin上实现它,因为它有点长,MS-PL可能与CC-Wiki不兼容。

使用这样的东西:

 private static void Main() { var mylist = new List {"abc", "DEF", "GHI"}; mylist.Should().EqualInsensitively(new[] {"AbC", "def", "GHI"}) .And.NotContain(string.Empty); //Emaple of chaining } 

你可以自己编写一个IEnumerable的扩展方法(这就是我做这个的东西)而且我的一些Unit-Testframeworks已经这样做了(FSUnit AFAIK)

这是一个简单的例子(你可以改进很多 – 但应该这样做)

 public static AssertEqualSetCaseInsensitive(this IEnumerable actual, IEnumerable expected) { if (actual.Count() != expected.Count()) Assert.Fail("not same number of elements"); if (!actual.All(a => expected.Any(e => e.ToLower() == a.ToLower())) Assert.Fail("not same sets"); } 

只是使用喜欢

 actual.AssertEqualSetCaseInsensitive(expected);