I am using Visual Studio 2017 and I was trying to create a unit test of a private method in C# (code below):
[TestClass]
public class CalculatorTests
{
[TestMethod]
public void TestCalculator_Hello()
{
var calc = new Calculator(1);
var privateObject = new PrivateObject(calc);
string expected = "hello!";
string result = privateObject.Invoke("HelloTest");
Assert.AreEqual(expected, result);
}
}
However, I got this error message:
Error CS0246 The type or namespace name 'PrivateObject' could not be found
I've looked up for articles and tutorials but I still don't know what I am doing wrong.
PrivateObject and PrivateType are not available for projects targeting netcoreapp2.0. There is a GitHub issue here: GitHub Issue 366
One option is to inherit from the class and then expose the method in the inherited class.
As @Tim mention it is not included on .net core https://github.com/Microsoft/testfx/issues/366 but if you follow the thread you can find a reference to https://gist.github.com/skalinets/1c4e5dbb4e86bd72bf491675901de5ad Which contains a "Poor man Private method implementation" for completeness the code is copied below
public class PrivateObject
{
private readonly object o;
public PrivateObject(object o)
{
this.o = o;
}
public object Invoke(string methodName, params object[] args)
{
var methodInfo = o.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
if (methodInfo == null)
{
throw new Exception($"Method'{methodName}' not found is class '{o.GetType()}'");
}
return methodInfo.Invoke(o, args);
}
}
I have tried it on a few unit tests and worked just fine for me, I will update if I find issues.
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