1

I am using Visual Studio 2019 and in a MSTest Test Project (.NET Core) I am trying to use PrivateObject to test a protected method.

For example, I'm trying to do something like following

PrivateObject private = new PrivateObject(new Color())

But I get the following error

PrivateObject could not be found are you missing a using directive or an assembly reference?

I am also including

using Microsoft.VisualStudio.TestTools.UnitTesting;

which I thought would include PrivateObject.

Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
  • 1
    Does this answer your question? [The type or namespace name 'PrivateObject' could not be found](https://stackoverflow.com/questions/53273228/the-type-or-namespace-name-privateobject-could-not-be-found) or [How to unit test private method in .Net Core application which does not support “PrivateObject”](https://stackoverflow.com/q/59678504/150605) – Lance U. Matthews Feb 05 '20 at 05:01

1 Answers1

2

I think PrivateObject does not exist in .Net Core. You can use these extensions to invoke non public members.

public static T CallNonPublicMethod<T>(this object o, string methodName, params object[] args)
        {
            var type = o.GetType();
            var mi = type.GetMethod(methodName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            if (mi != null)
            {
                return (T)mi.Invoke(o, args);
            }

            throw new Exception($"Method {methodName} does not exist on type {type.ToString()}");
        }

public static T CallNonPublicProperty<T>(this object o, string methodName)
        {
            var type = o.GetType();
            var mi = type.GetProperty(methodName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            if (mi != null)
            {
                return (T)mi.GetValue(o);
            }

            throw new Exception($"Property {methodName} does not exist on type {type.ToString()}");
        }

And you can use them like this:

var color= new Color();
var result= color.CallNonPublicMethod<YourReturnType>(YourMethodName, param1, param2, ... param n);
kkica
  • 4,034
  • 1
  • 20
  • 40
  • i tried var color = new color() and then var result = color.CallNonPublicMethod(getSizes); but it didn't work –  Feb 05 '20 at 21:20
  • @Golfer1145 How didn't it work? Please be specific; "it didn't work" doesn't tell Kristjan what is wrong. –  Feb 05 '20 at 21:36
  • You should have "GetSizes" as a string. Do you have a valid GetSizes method with no arguments? Show us what do you get. A compilation error, runtime exception? – kkica Feb 06 '20 at 05:08