在私有静态方法的C#中进行单元测试,接受其他私有静态方法作为委托参数

时间:2015-04-01 06:55:02

标签: c# unit-testing reflection delegates

我拥有的东西:我有一个非静态类,其中包含两个私有静态方法:其中一个可以作为委托参数传递给另一个:

public class MyClass
{
    ...

    private static string MyMethodToTest(int a, int b, Func<int, int, int> myDelegate)
    {
        return "result is " + myDelegate(a, b);
    }

    private static int MyDelegateMethod(int a, int b)
    {
        return (a + b);
    }
}

我需要做什么:我必须测试(使用单元测试)私有静态方法MyMethodToTest并将其作为委托参数传递给私有静态方法{{ 1}}。

我可以做什么:我知道如何测试私有静态方法,但我不知道如何将另一个与委托参数相同的私有静态方法传递给此方法

因此,如果我们假设MyDelegateMethod方法根本没有第三个参数,那么测试方法将如下所示:

MyMethodToTest

...

using System;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;

我的问题:如何测试私有静态方法作为委托参数传递给它的另一个私有静态方法?

1 个答案:

答案 0 :(得分:10)

这是怎么回事

[TestMethod]
        public void MyTest()
        {
            PrivateType privateType = new PrivateType(typeof(MyClass));

            var myPrivateDelegateMethod = typeof(MyClass).GetMethod("MyDelegateMethod", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
            var dele = myPrivateDelegateMethod.CreateDelegate(typeof(Func<int, int, int>));
            object[] parameterValues =
                        {
                            33,22,dele
                        };
            string result = (string)privateType.InvokeStatic("MyMethodToTest", parameterValues);
            Assert.IsTrue(result == "result is 55");
        }
相关问题