gpt4 book ai didi

c# - stub 静态扩展方法似乎在 Rhino Mocks 中有效,除非我强制转换返回变量。为什么?

转载 作者:太空狗 更新时间:2023-10-30 00:15:03 25 4
gpt4 key购买 nike

我可以使用 Rhino Mocks stub 静态扩展方法,但如果我将返回值转换为另一种类型,则会出现错误。为什么?

using Rhino.Mocks;

public interface INumberGenerator
{
double GetDouble();
}

static class NumberGeneratorExtensionMethods
{
public static double GetTheDouble(this INumberGenerator input)
{
return input.GetDouble();
}

public static decimal GetTheDoubleCastToDecimal(this INumberGenerator input)
{
return (decimal) input.GetDouble();
}
}

class MockExample
{
public void TriggerTheError()
{
var stub = MockRepository.GenerateStub<INumberGenerator>();

// This works
stub.Stub(obj => obj.GetTheDouble()).Return(1.2d);

// This throws the error
stub.Stub(obj => obj.GetTheDoubleCastToDecimal()).Return(1.2m);
}
}

这里是错误:

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

最佳答案

警告:这真的是一个比什么都重要的怀疑

问题是您根本没有真正对扩展方法进行 stub ——在这两种情况下您都在 stub GetDouble

我有一段时间没有查看 Rhino Mocks 的代码,但我怀疑 Stub 方法基本上是在说:

  • 准备好接听模拟电话!
  • 调用作为参数传入的委托(delegate)
  • 记下打了哪些电话

这意味着您正在有效地执行此操作:

canGetDecimal.Stub(ng => ng.GetDouble()).Return(1.2d);
canGetDecimal.Stub(ng => (decimal) ng.GetDouble()).Return(1.2m);

此时,它会注意到您调用了 GetDouble - 但随后您试图将返回值设置为 1.2m,这是无效的。

您可以很容易地通过一些日志记录来验证这一点。将日志行添加到 GetTheDoubleCastToDecimal,然后从 Return 调用中分离出 Stub 调用:

Console.WriteLine("Before Stub");
var stubCall = canGetDecimal.Stub(obj => obj.GetTheDoubleCastToDecimal();
Console.WriteLine("After Stub");
stubCall.Return(1.2m);

我强烈怀疑您会发现添加到扩展方法中的任何日志记录仍然记录在“ stub 之前”和“ stub 之后”之间 - 表明扩展方法没有被模拟出。

道德:不要尝试模拟/ stub 扩展方法。它们不是多态的;它们只是静态方法,如果没有深厚的魔法就很难伪造它们。只尝试伪造真正的多态操作。

关于c# - stub 静态扩展方法似乎在 Rhino Mocks 中有效,除非我强制转换返回变量。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17661979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com