C#中的單元測試私有方法 - Unit testing private methods in C#

問題:

Visual Studio allows unit testing of private methods via an automatically generated accessor class. Visual Studio 允許通過自動生成的訪問器類對私有方法進行單元測試。 I have written a test of a private method that compiles successfully, but it fails at runtime.我已經編寫了一個可以成功編譯的私有方法的測試,但它在運行時失敗。 A fairly minimal version of the code and the test is:代碼和測試的一個相當小的版本是:

//in project MyProj
class TypeA
{
    private List<TypeB> myList = new List<TypeB>();

    private class TypeB
    {
        public TypeB()
        {
        }
    }

    public TypeA()
    {
    }

    private void MyFunc()
    {
        //processing of myList that changes state of instance
    }
}    

//in project TestMyProj           
public void MyFuncTest()
{
    TypeA_Accessor target = new TypeA_Accessor();
    //following line is the one that throws exception
    target.myList.Add(new TypeA_Accessor.TypeB());
    target.MyFunc();

    //check changed state of target
}

The runtime error is:運行時錯誤是:

Object of type System.Collections.Generic.List`1[MyProj.TypeA.TypeA_Accessor+TypeB]' cannot be converted to type 'System.Collections.Generic.List`1[MyProj.TypeA.TypeA+TypeB]'.

According to intellisense - and hence I guess the compiler - target is of type TypeA_Accessor.根據智能感知 - 因此我猜編譯器 - 目標是 TypeA_Accessor 類型。 But at runtime it is of type TypeA, and hence the list add fails.但是在運行時它是 TypeA 類型,因此列表添加失敗。

Is there any way I can stop this error?有什麼辦法可以阻止這個錯誤嗎? Or, perhaps more likely, what other advice do other people have (I predict maybe "don't test private methods" and "don't have unit tests manipulate the state of objects").或者,也許更有可能的是,其他人有什麼其他建議(我預測可能“不要測試私有方法”和“不要讓單元測試操縱對象的狀態”)。


解決方案:

參考一: https://en.stackoom.com/question/cHES
參考二: https://stackoom.com/question/cHES
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章