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

I am following this tutorial, https://docs.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.



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1