【发布时间】:2014-01-17 16:51:55
【问题描述】:
我正在尝试在循环中设置一个模拟对象,该对象将为具有不同参数的函数调用返回不同的值:
var myMock= new Mock<IInterface>();
for (int i = 0; i < fromKeys.Count; ++i)
{
var value= new[] {new[] {1.0 + i}};
_values.Add(value);
myMock.Setup(x => x.Provide(fromKeys[i])).Returns(new Sth(fromKeys[i], value));
}
_myObject = myMock.Object;
但是当我使用生产代码中的第一个键调用 Provide 时它会崩溃(而不是在测试设置期间):
System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
----> System.ArgumentOutOfRangeException : Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, ref SignatureStruct sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at Moq.Evaluator.SubtreeEvaluator.Evaluate(Expression e)
at Moq.Matchers.LazyEvalMatcher.Matches(Object value)
at Moq.MethodCall.Matches(ICallContext call)
at System.Linq.Enumerable.LastOrDefault(IEnumerable`1 source, Func`2 predicate)
at Moq.ExtractProxyCall.HandleIntercept(ICallContext invocation, InterceptStrategyContext ctx)
at Moq.Interceptor.Intercept(ICallContext invocation)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.IBrownianProviderProxy.Provide(BrowniansKey keys)
at MyCode.....
如何设置?
【问题讨论】:
-
这和闭包有关系吗?尝试在循环内
myMock.Setup()行之前添加一行:int j = i;,然后在模拟设置中使用j而不是i。 -
你是如何设置_values的?
-
看起来 _values 是个问题。能否提供设置_values的代码?
-
@AdarshShah,值实际上是在同一个循环中创建的,请参阅编辑。崩溃是在我调用模拟上的方法时,而不是在我设置它时。
-
@TheMouthofaCow,请参阅编辑。
标签: c# .net unit-testing mocking moq