Visual Studio 允许通过自动生成的访问器类对私有方法进行单元测试。我编写了一个私有方法的测试,该方法编译成功,但在运行时失败。代码和测试的相当最小的版本是:
//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
}
运行时错误是:
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]'.
根据智能感知 - 因此我猜测编译器 - 目标是 TypeA_Accessor 类型。但在运行时它是 TypeA 类型,因此列表添加失败。
有什么办法可以阻止这个错误吗?或者,也许更有可能的是,其他人还有什么其他建议(我预测可能是“不要测试私有方法”和“不要让单元测试操纵对象的状态”)。
如果使用 .NET Core 2.0 之前的版本,您可以使用PrivateObject https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.privateobject class:
Class target = new Class();
PrivateObject obj = new PrivateObject(target);
var retVal = obj.Invoke("PrivateMethod");
Assert.AreEqual(expectedVal, retVal);
PrivateObject and PrivateType.NET Core 2.0 中删除了支持。 https://github.com/Microsoft/testfx/issues/366#issuecomment-580147403
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)