Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

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?

like image 319
Jordan Avatar asked Apr 01 '15 06:04

Jordan


1 Answers

Here is how it should go

[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");
}
like image 119
Anwer Matter Avatar answered Sep 18 '22 12:09

Anwer Matter