C# 断言数组在 Visual Studio 2008 测试框架中相等
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/897552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assert that arrays are equal in Visual Studio 2008 test framework
提问by Anteru
Is there an easy way to check in a unit test that two arrays are equal (that is, have the same number of elements, and each element is the same?).
是否有一种简单的方法可以在单元测试中检查两个数组是否相等(即具有相同数量的元素,并且每个元素都相同?)。
In Java, I would use assertArrayEquals (foo, bar);
, but there seems to be no equivalent for C#. I tried Assert.AreEqual(new string[]{"a", "b"}, MyFunc("ab"));
, but even though the function returns an array with "a", "b" the check still fails
在 Java 中,我会使用assertArrayEquals (foo, bar);
,但似乎没有 C# 的等价物。我试过了Assert.AreEqual(new string[]{"a", "b"}, MyFunc("ab"));
,但即使函数返回一个带有“a”、“b”的数组,检查仍然失败
This is using Visual Studio 2008 Team Suite, with the built-in unit test framework.
这是使用带有内置单元测试框架的 Visual Studio 2008 Team Suite。
采纳答案by Anteru
It's CollectionAssert.AreEqual
, see also the documentation for CollectionAssert.
它是CollectionAssert.AreEqual
,另请参阅CollectionAssert的文档。
回答by Marc Gravell
In .NET 3.5, perhaps consider Assert.IsTrue(foo.SequenceEqual(bar));
- it won't tell you at what index it differs, though.
在 .NET 3.5 中,也许考虑一下Assert.IsTrue(foo.SequenceEqual(bar));
- 但是它不会告诉你它在什么索引上有所不同。
回答by Autodidact
Ok here is a slightly longer way of doing it...
好的,这是一种稍微长一点的方法......
static void Main(string[] args)
{
var arr1 = new[] { 1, 2, 3, 4, 5 };
var arr2 = new[] { 1, 2, 4, 4, 5 };
Console.WriteLine("Arrays are equal: {0}", equals(arr1, arr2));
}
private static bool equals(IEnumerable arr1, IEnumerable arr2)
{
var enumerable1 = arr1.OfType<object>();
var enumerable2 = arr2.OfType<object>();
if (enumerable1.Count() != enumerable2.Count())
return false;
var iter1 = enumerable1.GetEnumerator();
var iter2 = enumerable2.GetEnumerator();
while (iter1.MoveNext() && iter2.MoveNext())
{
if (!iter1.Current.Equals(iter2.Current))
return false;
}
return true;
}
回答by Erix Xu
Class1.cs:
Class1.cs:
namespace ClassLibrary1
{
public class Class1
{
Array arr1 = new[] { 1, 2, 3, 4, 5 };
public Array getArray()
{
return arr1;
}
}
}
ArrayEqualTest.cs:
ArrayEqualTest.cs:
[TestMethod()]
public void getArrayTest()
{
Class1 target = new Class1();
Array expected = new []{1,2,3,4,5};
Array actual;
actual = target.getArray();
CollectionAssert.AreEqual(expected, actual);
//Assert.IsTrue(expected.S actual, "is the test results");
}
Test Success,found the error:
测试成功,发现错误:
CollectionAssert.AreEqual failed. (Element at index 3 do not match.)