Álvaro García
Álvaro García

Reputation: 19356

How to test a PrivateObject in a .net standard test project?

I am following this tutorial, https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-with-mstest

but I don't have the type PrivateObject available, so I am wondering if it would be possible to test private objects with a .net standard 2.0 project.

Upvotes: 4

Views: 1851

Answers (2)

Олег Рубан
Олег Рубан

Reputation: 21

You can always use a reflection

ClassToTest obj = new ClassToTest();
Type t = typeof(ClassToTest);

FieldInfo f = t.GetField("field",  BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
f.SetValue(obj, "Don't panic");

t.InvokeMember("PrintField",
    BindingFlags.InvokeMethod | BindingFlags.NonPublic |
    BindingFlags.Public | BindingFlags.Instance,
    null, obj, null);

You should write a helper class for this, or else your tests will conatin a lot of identical code

P.S. Sample of code is from here

Upvotes: 2

Kirhgoph
Kirhgoph

Reputation: 415

Private objects are accessible only within the body of the class, so in order to test them you must do one of the following:

  1. make private objects public or
  2. implement public methods which will interact with these private objects

Upvotes: -1

Related Questions