【问题标题】:Unit testing in C# of private-static method accepting other private-static method as a delegate parameterC# 中的私有静态方法单元测试接受其他私有静态方法作为委托参数
【发布时间】:2015-06-05 17:41:07
【问题描述】:

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

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 作为委托参数传递给它。

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

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

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

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

【问题讨论】:

  • 你为什么要测试一个与另一个?如果您总是将 MyDelegateMethod 传递给 MyMethodToTest,那么您应该将该代码移至 MyMethodToTest。如果没有,那么您应该能够与任何代表一起测试它。您可以将 Func 创建为对象并将其作为参数传递。
  • 这只是一张简化图。事实上,我在这个类中有很多类似MyDelegateMethod 的方法。它们非常简单,不需要进行测试。最复杂的部分是MyMethodToTest 方法,必须对其进行测试。显然,可以在测试类中编写类似MyDelegateMethod 的方法的副本,并将它们作为委托参数传递给MyMethodToTest 方法(我没有尝试),但我想避免重复。

标签: c# unit-testing reflection delegates


【解决方案1】:

应该是这样的

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

【讨论】:

  • 谢谢!有用!只说一句:局部变量parameterTypes没有使用,也不需要。
  • 取出这一行 var dele = myPrivateDelegateMethod.CreateDelegate(typeof(Func));效果很好!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2012-07-14
  • 2017-06-19
  • 2017-10-08
  • 2016-06-28
  • 2015-04-17
相关资源
最近更新 更多