c# - 犀牛模拟 : How to stub a generic method to catch an anonymous type?

标签 c# unit-testing generics rhino-mocks

我们需要 stub 一个通用方法,该方法将使用匿名类型作为类型参数来调用。考虑:

interface IProgressReporter
{
    T Report<T>(T progressUpdater);
}

// Unit test arrange:
Func<object, object> returnArg = (x => x);   // we wish to return the argument
_reporter.Stub(x => x.Report<object>(null).IgnoreArguments().Do(returnArg);

如果在被测方法中对 .Report() 的实际调用是使用对象作为类型参数完成的,那么这将起作用,但实际上,调用该方法时使用的 T 是匿名类型。此类型在被测方法之外不可用。因此,永远不会调用 stub 。

是否可以在不指定类型参数的情况下对泛型方法进行 stub ?

最佳答案

我不清楚您的用例,但您可以使用辅助方法为每个测试设置 stub 。我没有 RhinoMocks,所以无法验证这是否有效

private void HelperMethod<T>()
{
  Func<object, object> returnArg = (x => x); // or use T in place of object if thats what you require
  _reporter.Stub(x => x.Report<T>(null)).IgnoreArguments().Do(returnArg);
}

然后在你的测试中做:

public void MyTest()
{
   HelperMethod<yourtype>();
   // rest of your test code
}

关于c# - 犀牛模拟 : How to stub a generic method to catch an anonymous type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6186412/

相关文章:

c# - 自定义属性和 GetCustomAttributes 的奇怪行为

c# - 如何检测隐藏的桌面?

c# - Task<T> 异步导致 Xamarin.iPhone (MonoTouch) JIT 错误?

java - Maven 和单元测试 - 结合 Maven Surefire 插件和 testNG Eclipse 插件

generics - 注入(inject)由抽象类型参数化的类型化类

java - 为什么 LongProperty 实现了 Property<Number> 而不是 Property<Long>?

c# - 如何使用 C# 按顺时针方向打印 4x4 数组

ruby - 是否可以在不调用初始化的情况下实例化 Ruby 类?

java - 获取泛型类型的数组类

java - 什么时候在java中使用@Override