有没有一种简单的方法来检查单元测试中两个数组是否相等(即,具有相同数量的元素,并且每个元素是相同的?).
在Java中,我会使用assertArrayEquals (foo, bar);,但似乎没有C#的等价物.我试过Assert.AreEqual(new string[]{"a", "b"}, MyFunc("ab"));,但即使函数返回一个带有"a","b"的数组,检查仍然失败
这是使用Visual Studio 2008 Team Suite,内置单元测试框架.
它似乎CollectionAssert不能与泛型一起使用.这太令人沮丧了; 我想测试的代码确实使用了泛型.我是什么做的?写样板文件在两者之间转换?手动检查集合等价?
这失败了:
ICollection<IDictionary<string, string>> expected = // ...
IEnumerable<IDictionary<string, string>> actual = // ...
// error 1 and 2 here
CollectionAssert.AreEqual(expected.GetEnumerator().ToList(), actual.ToList());
// error 3 here
Assert.IsTrue(expected.GetEnumerator().SequenceEquals(actual));
Run Code Online (Sandbox Code Playgroud)
编译器错误:
错误1:
'System.Collections.Generic.IEnumerator>'不包含'ToList'的定义,并且没有可以找到接受类型'System.Collections.Generic.IEnumerator>'的第一个参数的扩展方法'ToList'
错误2
'System.Collections.Generic.IEnumerator>'不包含'ToList'的定义,并且没有可以找到接受类型'System.Collections.Generic.IEnumerator>'的第一个参数的扩展方法'ToList'
错误3
'System.Collections.Generic.IEnumerator>'不包含'SequenceEquals'的定义,并且没有可以找到接受类型'System.Collections.Generic.IEnumerator>'的第一个参数的扩展方法'SequenceEquals'
我究竟做错了什么?我没有正确使用扩展程序吗?
更新:好的,这看起来好一点,但仍然不起作用:
IEnumerable<IDictionary<string, string>> expected = // ...
IEnumerable<IDictionary<string, string>> actual = // ...
CollectionAssert.AreEquivalent(expected.ToList(), actual.ToList()); // fails
CollectionAssert.IsSubsetOf(expected.ToList(), actual.ToList()); // fails
Run Code Online (Sandbox Code Playgroud)
我不想比较名单; 我只关心集合成员平等.成员的顺序并不重要.我怎么能绕过这个?
MSTest框架有一个CollectionAssert,可以接受ICollections.我的方法返回一个IList.显然列表不是集合..
有没有办法让我的IList成为ICollection?
我目前正在尝试学习如何使用单元测试,并且我已经创建了 3 个动物对象的实际列表和 3 个动物对象的预期列表。问题是我如何断言检查列表是否相等?我试过 CollectionAssert.AreEqual 和 Assert.AreEqual 但无济于事。任何帮助,将不胜感激。
测试方法:
[TestMethod]
public void createAnimalsTest2()
{
animalHandler animalHandler = new animalHandler();
// arrange
List<Animal> expected = new List<Animal>();
Animal dog = new Dog("",0);
Animal cat = new Cat("",0);
Animal mouse = new Mouse("",0);
expected.Add(dog);
expected.Add(cat);
expected.Add(mouse);
//actual
List<Animal> actual = animalHandler.createAnimals("","","",0,0,0);
//assert
//this is the line that does not evaluate as true
Assert.Equals(expected ,actual);
}
Run Code Online (Sandbox Code Playgroud)