var x = new List() { new List() }; var y = new List() { new List() }; CollectionAssert.AreEqual(x, y, "Expected response not the same as actual response.");
作为替代方案,您可以考虑使用与Microsoft Unit Test兼容的FluentAssertions Unit Test框架。
然后你的代码将成为:
var x = new List
它也适用于这种事情:
var ints1 = new List(); var ints2 = new List(); ints1.Add(1); ints2.Add(1); var x = new List() { ints1 }; var y = new List() { ints2 }; x.ShouldBeEquivalentTo(y, "Expected response not the same as actual response.");
如果你改变了ints2.Add(1); to ints2.Add(2); ,然后unit testing将正确失败。
var ints1 = new List(); var ints2 = new List(); ints1.Add(1); ints2.Add(1); // Change this to .Add(2) and the unit test fails. var objList1 = new List { ints1 }; var objList2 = new List { ints2 }; var x = new List { objList1 }; var y = new List { objList2 }; x.ShouldBeEquivalentTo(y, "Expected response not the same as actual response.");
List list = new List(); var x = new List() { list }; var y = new List() { list }; CollectionAssert.AreEqual(x, y, "Expected response not the same as actual response.");
您会发现此传递作为列表,满足CollectionAssert.AreEqual的参数参数。
希望这可以解决它。
这是因为
new List().Equals(new List())
返回False 。 外部列表不相等,因为内部列表不相等。
您可以尝试使用接受IComparer的重载 ,它会将您的两个空列表视为相等。
您应该使用SelectMany提取外部列表的内容,然后检查是否相等,例如:
var x = new List() { new List() }; var y = new List() { new List() }; var xItems=x.SelectMany(item=>item); var yItems=y.SelectMany(item=>item); CollectionAssert.AreEqual(xItems, yItems, "Expected response not the same as actual response.");
[TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { var x = new List() { new List(){1} }; var y = new List() { new List(){1} }; x.SequenceRecursiveEqual(y); } } public static class ExtenderListAssert { public static void SequenceRecursiveEqual(this IList sourse, IList expected) { if (sourse.Count != expected.Count) Assert.Fail(); else { for (var i = 0; i < sourse.Count; i++) { var left = sourse[i]; var right = expected[i]; if(left is IList && right is IList) { (left as IList).SequenceRecursiveEqual(right as IList); } else { Assert.AreEqual(left, right); } } } } }
您可以使用SequenceEqual并检查返回的bool以进行断言
使用此类型:
[TestMethod] public void AreEqualTest1() { List countries1 = new List { "Israel", "USA", "Germany" }; List countries2 = new List { "Israel", "USA", "Germany" }; // First compare count of both collections:countries1 && countries2 => // if not the same count => test failed. // Otherwise copmare the equality items of both collections in order, // if one of the comparison failed => test failed // otherwise =>=> test passed. CollectionAssert.AreEqual(countries1, countries2, "Not equal, hence failed"); }