我们如何在不实例化测试类中的对象的情况下测试void方法?我了解在内部静态类中,我们无法使用“新”来创建对象来对其进行测试。我已经通过为非静态类创建对象进行了单元测试,但是我还没有处理内部静态类并且陷入困境。任何指导都会很棒。

这是有问题的类/方法:

internal static class Util
{
    public static void AssertBytesEqual(byte[] expected, byte[] actual)
    {
        if (expected.Length != actual.Length)
        {
            Debugger.Break();
            throw new CryptographicException("The bytes were not of the expected length.");
        }

        for (int i = 0; i < expected.Length; i++)
        {
            if (expected[i] != actual[i])
            {
                Debugger.Break();
                throw new CryptographicException("The bytes were not identical.");
            }
        }
    }
}

最佳答案

您可以使用InternalsVisibileTo属性来允许另一个项目访问内部类。

[assembly: InternalsVisibleTo("NameOfYourUnitTestProject")]


这将允许您的测试项目调用Util.AssertBytesEqual。通常将应用程序集级别的属性放在AssemblyInfo.cs文件中。

至于测试实际的方法本身,看起来是唯一的“输出”,可以说是一个例外。您只需测试该方法是否为各种输入引发异常。

07-28 03:40
查看更多