【问题标题】:Moq expectations on the same method call with different argumentsMoq 对具有不同参数的同一方法调用的期望
【发布时间】: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


【解决方案1】:

这是一个闭包问题。 x =&gt; 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]));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 2017-09-06
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多