【问题标题】:Unit testing a void method in an internal static class在内部静态类中对 void 方法进行单元测试
【发布时间】:2017-09-26 22:25:57
【问题描述】:

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

这是有问题的类/方法:

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.");
            }
        }
    }
}

【问题讨论】:

    标签: c# unit-testing testing methods void


    【解决方案1】:

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

    [assembly: InternalsVisibleTo("NameOfYourUnitTestProject")]
    

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

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

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 2017-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多