尝试使用 Moq 设置索引器属性时,底层 Castle 库会引发 InvalidCastException。我使用的是最小起订量 4.0.10827,详情如下。如果有人可以帮助我运行简单的测试(如下),请提前致谢。我正在用 Moq 重写单元测试,我正在尝试为以下方法重新进行测试:
public INetwork GetInputNetwork(IInputPortMgr inPortMgr)
{
var port = inPortMgr[0];
return port.InputNetwork;
}
IInputPortMgr 接口如下:
public interface IInputPortMgr
{
IInputPort this[int index] { get; }
}
我编写的测试(并尝试了许多变体)可以总结为:
[Test]
public void GetInputNetwork_Returns_InputNetwork_From_InputPort()
{
var mockInPortMgr = new Mock<IInputPortMgr>();
var mockInPort = new Mock<IInputPort>();
var mockNet = new Mock<INetwork>();
mockInPortMgr.Setup(m => m[0]).Returns(mockInPort.Object); // exception here
mockInPort.Setup(m => m.InputNetwork).Returns(mockNet.Object);
// Assertions Here
}
但是当运行单元测试失败时,因为该行抛出异常
mockInPortMgr.Setup(m => m[0]).Returns(mockInPort.Object);
异常详情如下:
System.InvalidCastException : Unable to cast object of type 'System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument]' to type 'System.Array'.
at System.Reflection.Emit.CustomAttributeBuilder.EmitValue(BinaryWriter writer, Type type, Object value)
at System.Reflection.Emit.CustomAttributeBuilder.InitCustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs, PropertyInfo[] namedProperties, Object[] propertyValues, FieldInfo[] namedFields, Object[] fieldValues)
at Castle.DynamicProxy.AttributeUtil.CreateBuilder(CustomAttributeData attribute)
at Castle.DynamicProxy.AttributeUtil.<GetNonInheritableAttributes>d__0.MoveNext()
at Castle.DynamicProxy.Generators.MetaProperty.BuildPropertyEmitter(ClassEmitter classEmitter)
at Castle.DynamicProxy.Contributors.CompositeTypeContributor.ImplementProperty(ClassEmitter emitter, MetaProperty property, ProxyGenerationOptions options)
at Castle.DynamicProxy.Contributors.CompositeTypeContributor.Generate(ClassEmitter class, ProxyGenerationOptions options)
at Castle.DynamicProxy.Generators.InterfaceProxyWithoutTargetGenerator.GenerateType(String typeName, Type proxyTargetType, Type[] interfaces, INamingScope namingScope)
at Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.GenerateCode(Type proxyTargetType, Type[] interfaces, ProxyGenerationOptions options)
at Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyWithoutTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, IInterceptor[] interceptors)
at Moq.Proxy.CastleProxyFactory.CreateProxy(ICallInterceptor interceptor, Type[] interfaces, Object[] arguments)
at Moq.Mock`1.<InitializeInstance>b__0()
at Moq.Mock`1.InitializeInstance()
at Moq.Mock`1.OnGetObject()
at Moq.Mock`1.get_Object()
at Tests.Psi.Type6.Fx.Type6Fixture.GetInputNetwork() in Type6Fixture.cs: line 293
任何想法或任何人都可以指出我正确的方向吗?谢谢。