Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The type or namespace name 'PrivateObject' could not be found

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.

like image 343
Paulo Avatar asked Nov 13 '18 03:11

Paulo


2 Answers

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.

like image 160
Tim Avatar answered Nov 15 '22 08:11

Tim


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.

like image 26
J.J Avatar answered Nov 15 '22 06:11

J.J