编辑:我玩过这个例子,现在 my question is a different one entirely .
当我运行这个例子时:
using Rhino.Mocks;
public interface IInterface
{
decimal GetDecimal();
}
static class Util
{
public static double? DecToDouble(this IInterface input)
{
return (double) input.GetDecimal();
}
}
class MockExample
{
public void RunThis()
{
var stubReader = MockRepository.GenerateStub<IInterface>();
stubReader.Stub(sr => sr.DecToDouble()).Return(1.2);
}
}
我收到这个错误:
System.InvalidOperationException : Type 'System.Double' doesn't match the return type 'System.Decimal' for method 'IInterface.GetDecimal();'
为什么?
请您参考如下方法:
Rhino Mocks 只能拦截通过 stub 接口(interface)进行的调用。上面的扩展方法被编译成类似这样的东西:
Util.DecToDouble(sr)
这意味着您的设置/返回基本上是这样的:
stubReader.Stub(sr => Util.DecToDouble(sr)).Return(1.2);
这显然行不通(对于大多数模拟框架)。实现你想要的正确方法是:
stubReader.Stub(sr => sr.GetDecimal())).Return(1.2);
经过进一步调查: Rhino Mocks 通过调用传递给 Stub() 的委托(delegate)并保存最后应用的方法调用,在内部将 Stub() 声明的方法连接到 Return() 声明的值。这个保存的方法调用随后连接到返回值。执行此操作时,Rhino Mocks 会在内部检查保存的调用的返回类型是否与值的类型匹配。如果它们不匹配,Rhino Mocks 会引发您看到的异常。定义 stub 的正确方法是
decimal val = 1.2M;
stubReader.Stub(sr => sr.DecToDouble()).Return(val);
但这不会编译,因为 Stub() 和 Return() 的泛型类型参数必须兼容。所以真正定义 stub 的唯一方法是忽略扩展方法,只 stub 接口(interface)中定义的方法。
