问题:
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