C#中的私有静态方法的单元测试接受其他私有静态方法作为委托参数 [英] Unit testing in C# of private-static method accepting other private-static method as a delegate parameter
问题描述
我所拥有的:我有一个非静态类,其中包含两个私有静态方法:其中一个可以作为委托参数传递给另一个:
What I have: I have a non-static class containing, among others, two private-static methods: one of them can be passed to another one as a delegate parameter:
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
,并将私有静态方法 MyDelegateMethod传递给它作为委托参数
。
What I have to do: I have to test (with unit testing) the private-static method MyMethodToTest
with passing to it as the delegate parameter the private-static method MyDelegateMethod
.
我可以做什么:我知道如何测试私有静态方法,但是我不知道知道如何将与委托参数相同类的另一个私有静态方法传递给此方法。
What I can do: I know how to test a private-static method, but I do not know how to pass to this method another private-static method of the same class as a delegate parameter.
因此,如果我们假设 MyMethodToTest
方法根本没有第三个参数,测试方法将如下所示:
So, if we assume that the MyMethodToTest
method has no the third parameter at all, the test method will look like:
using System;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
...
[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");
}
我的问题:如何测试私有-静态方法作为委托参数传递给它的另一个相同类的私有静态方法?
My question: How to test a private-static method passing to it as a delegate parameter another private-static method of the same class?
推荐答案
这是它应该怎么做的
[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");
}
这篇关于C#中的私有静态方法的单元测试接受其他私有静态方法作为委托参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!