繁体   English   中英

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

[英]Can Fluent Assertions use a string-insensitive comparison for IEnumerable<string>?

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

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

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

  actual.Should().Equal(expected);
}

在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)。

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

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

  actual.Should().Equal(expected, 
    (o1, o2) => string.Compare(o1, o2, StringComparison.InvariantCultureIgnoreCase))
} 

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

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

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

使用这样的东西:

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

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

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

public static AssertEqualSetCaseInsensitive(this IEnumerable<string> actual, IEnumerable<string> 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM