C# unit testing private methods: avoiding runtime errors
In C#, you can use Visual Studio's automatically generated accessor classes to unit test private methods. However, runtime errors may occur when trying to manipulate the object's internal state through these tests.
Fundamental problem
The error encountered in the provided code is due to the accessor class target being treated as TypeA_Accessor at compile time, but treated as TypeA at runtime. This mismatch causes the Add() operation on target.myList to fail because the list types are different.
Resolving errors
In versions prior to .NET Core 2.0, you can use the PrivateObject class to access private methods. This requires the following steps:
<code class="language-csharp">Class target = new Class(); PrivateObject obj = new PrivateObject(target); var retVal = obj.Invoke("PrivateMethod"); Assert.AreEqual(expectedVal, retVal);</code>
Alternative methods
Instead of testing private methods directly, consider the following alternative:
Please note that PrivateObject and PrivateType support have been removed in .NET Core 2.0 and later, requiring alternative methods to access and test private methods in newer versions of the framework.
The above is the detailed content of How Can I Unit Test Private Methods in C# and Avoid Runtime Errors?. For more information, please follow other related articles on the PHP Chinese website!