[英]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.