Home >Backend Development >C++ >How Can I Effectively Test Private Methods in C# When Facing Type Discrepancies?

How Can I Effectively Test Private Methods in C# When Facing Type Discrepancies?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-18 21:47:10198browse

How Can I Effectively Test Private Methods in C# When Facing Type Discrepancies?

C# Private Method Test

To achieve full code coverage, private methods need to be tested. One way is to use the accessor classes generated by Visual Studio. However, this approach may encounter runtime errors due to type mismatch.

Consider the following code snippet:

<code class="language-csharp">// 在MyProj项目中
class TypeA
{
    private List<TypeB> myList = new List<TypeB>();

    private class TypeB
    {
        public TypeB()
        {
        }
    }

    public TypeA()
    {
    }

    private void MyFunc()
    {
        // 更改实例状态的myList处理
    }
}</code>

Question:

The unit test for private method MyFunc fails at runtime with the following error:

<code>无法将类型为'System.Collections.Generic.List`1[MyProj.TypeA.TypeA_Accessor+TypeB]'的对象转换为类型为'System.Collections.Generic.List`1[MyProj.TypeA.TypeA+TypeB]'的对象。</code>

This is because the accessor class generates different implementations of myList with different type parameters.

Solution:

In versions of .NET Core earlier than 2.0, you can use the PrivateObject class to call private methods:

<code class="language-csharp">// 在TestMyProj项目中
public void MyFuncTest()
{
    TypeA target = new TypeA();
    PrivateObject obj = new PrivateObject(target);
    // 下一行不会抛出异常
    obj.Invoke("myList", new object[] { new TypeA_Accessor.TypeB() });
    obj.Invoke("MyFunc");

    // 检查target的更改状态
}</code>

However, .NET Core 2.0 and later has removed support for PrivateObject and PrivateType. In this case, consider refactoring the code to make the private methods testable, or adopt a reflection-based approach.

The above is the detailed content of How Can I Effectively Test Private Methods in C# When Facing Type Discrepancies?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn