在C#中测试私有方法的单元
Visual Studio允许通过自动生成的访问器类对私有方法进行单元测试。我编写了一个成功编译的私有方法的测试,但它在运行时失败了。一个相当小的代码和测试版本是:
//in project MyProjclass 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}
运行时错误是:
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]'.
根据intellisense - 因此我猜编译器 - 目标是TypeA_Accessor类型。但在运行时它的类型为TypeA,因此列表添加失败。
有什么办法可以阻止这个错误吗?或者,或许更有可能的是,其他人有什么其他建议(我预测可能“不测试私有方法”和“没有单元测试操纵对象的状态”)。