c# - VS 2010 单元测试和无符号类型

标签 c# unit-testing nunit migration mstest

我正在将我的单元测试从 NUnit 转换到 VisualStudio 2010 单元测试框架。以下ByteToUShortTest()方法失败并显示消息:

Assert.AreEqual failed. Expected:<System.UInt16[]>. Actual:<System.UInt16[]>.

[TestMethod, CLSCompliant(false)]
public void ByteToUShortTest()
{
    var array = new byte[2];
    Assert.AreEqual(ByteToUShort(array), new ushort[1]);
}

测试调用的代码是:

[CLSCompliant(false)]
public static ushort[] ByteToUShort(byte[] array)
{
    return ByteToUShort(array, 0, array.Length, EndianType.LittleEndian);
}

public enum EndianType
{
    LittleEndian,
    BigEndian
}

[CLSCompliant(false)]
public static ushort[] ByteToUShort(byte[] array, int offset, int length, EndianType endianType)
{
    // argument validation
    if ((length + offset) > array.Length)
        throw new ArgumentException("The length and offset provided extend past the end of the array.");
    if ((length % 2) != 0)
        throw new ArgumentException("The number of bytes to convert must be a multiple of 2.", "length");

    var temp = new ushort[length / 2];

    for (int i = 0, j = offset; i < temp.Length; i++)
    {
        if (endianType == EndianType.LittleEndian)
        {
            temp[i] = (ushort)(((uint)array[j++] & 0xFF) | (((uint)array[j++] & 0xFF) << 8));
        }
        else
        {
            temp[i] = (ushort)(((uint)array[j++] & 0xFF) << 8 | ((uint)array[j++] & 0xFF));
        }
    }

    return temp;
}

此测试使用 NUnit 成功运行。知道为什么类型应该不同吗?

解决方案

对于一维和多维数组,以及任何ICollection , VisualStudio 2010 单元测试框架提供了 CollectionAssert类(class)。

[TestMethod, CLSCompliant(false)]
public void ByteToUShortTest()
{
    var array = new byte[2];
    CollectionAssert.AreEqual(ByteToUShort(array), new ushort[1]);
}

最佳答案

不同的不是类型,而是实例。您正在比较两个不同的数组。

关于c# - VS 2010 单元测试和无符号类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1102097/

相关文章:

c# - 如何为 IGrouping 设置 NUnit 模拟对象

unit-testing - 如何用Moq模拟对具体对象的函数调用?

php - 在phpunit中, "with"方法内部是否有类似于onconsecutivecalls的方法?

nunit - 是否可以自定义 NUnit XML 输出?

c# - 检查自打开表单后文本框文本是否已更改

c# - 对象数组动态

c# - 查找面板中文本的高度

c# - 如何以编程方式创建 ASP.NET MVC 项目?

c++ - 库单元测试的错误覆盖率数据

asp.net-mvc-4 - 使用 Kendo 对 ASP.NET MVC4 Controller 进行单元测试