使用 Rhino Mocks 的奇怪错误“类型与返回值不匹配" [英] Weird error using Rhino Mocks "type doesn't match the return value"

查看:43
本文介绍了使用 Rhino Mocks 的奇怪错误“类型与返回值不匹配"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我玩过这个例子,现在 我的问题完全不同.

I played with this example and now 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 : 类型System.Double"与方法IInterface.GetDecimal();"的返回类型System.Decimal"不匹配

System.InvalidOperationException : Type 'System.Double' doesn't match the return type 'System.Decimal' for method 'IInterface.GetDecimal();'

为什么?

推荐答案

Rhino Mocks 只能拦截通过存根接口发出的调用.上面的扩展方法被编译成这样:

Rhino Mocks can only intercept calls that are made through the stubbed interface. The extension method above is compiled to something like:

Util.DecToDouble(sr)

这意味着您的设置/返回基本上是这样的:

This means that your setup/return basically reads like this:

stubReader.Stub(sr => Util.DecToDouble(sr)).Return(1.2);

这显然行不通(对于大多数模拟框架).实现您想要的正确方法是:

That clearly is not going to work (with most mocking frameworks). The proper way to achieve what you want is:

stubReader.Stub(sr => sr.GetDecimal())).Return(1.2);

经过进一步调查:Rhino Mocks 通过调用传递给 Stub() 的委托并保存最后应用的方法调用,在内部将 Stub() 声明的方法连接到 Return() 声明的值.这个保存的方法调用随后连接到返回值.执行此操作时,Rhino Mocks 会在内部检查保存调用的返回类型是否与值的类型匹配.如果它们与 Rhino Mocks 不匹配,则会引发您所看到的异常.定义存根的正确方法是

After further investigation: Rhino Mocks internally connects the method declared by Stub() to the value declared by Return() by invoking the delegate passed to Stub() and saving the last applied method invocation. This saved method invocation is afterwards connected to the return value. When doing this Rhino Mocks internally checks whether the return type of the saved invocation matches the type of the value. If they don't match Rhino Mocks raises the exception you are seeing. The correct way to define the stubbing would be

    decimal val = 1.2M;
    stubReader.Stub(sr => sr.DecToDouble()).Return(val);

但这不会编译,因为 Stub() 和 Return() 的泛型类型参数必须兼容.所以真正定义存根的唯一方法是忽略扩展方法,只存根接口中定义的方法.

But this does not compile, because the generic type params of Stub() and Return() must be compatible. So really the only way to define the stubbing is to ignore the extension methods and only stub the methods defined in the interface.

这篇关于使用 Rhino Mocks 的奇怪错误“类型与返回值不匹配"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆