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?
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With