Grz*_*nio 1 .net c# unit-testing moq mocking
我试图在循环中设置一个模拟对象,它将为具有不同参数的函数调用返回不同的值:
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;
Run Code Online (Sandbox Code Playgroud)
但是当我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.....
Run Code Online (Sandbox Code Playgroud)
我该如何设置?
这是一个封闭问题. x => x.Provide(fromKeys[i])直到稍后才评估.当它稍后被评估时,i== fromKeys.Count,这超出了数组的范围.如果这没有意义,我建议更多地了解关闭.但是,简单的解决方案是添加一行,以便您的代码看起来像这样(在for循环中)
for (int i = 0; i < fromKeys.Count; ++i)
{
int j = i;
myMock.Setup(x => x.Provide(fromKeys[j])).Returns(new Sth(fromKeys[j], _values[j]));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1422 次 |
| 最近记录: |