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

Jor*_*dan 3 c# reflection delegates unit-testing

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我要做的事情:我必须测试(使用单元测试)私有静态方法MyMethodToTest,并将私有静态方法作为委托参数传递给它MyDelegateMethod.

我能做什么:我知道如何测试私有静态方法,但我不知道如何将同一个类的另一个私有静态方法作为委托参数传递给此方法.

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

using System;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
Run Code Online (Sandbox Code Playgroud)

...

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

    Type[] parameterTypes =
    {
        typeof(int),
        typeof(int)
    };

    object[] parameterValues =
    {
        33,
        22
    };

    string result = (string)privateType.InvokeStatic("MyMethodToTest", parameterTypes, parameterValues);

    Assert.IsTrue(result == "result is 55");
}
Run Code Online (Sandbox Code Playgroud)

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

小智 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");
}
Run Code Online (Sandbox Code Playgroud)