Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Rhino Mocks:如何存根泛型方法以捕获匿名类型?_C#_Unit Testing_Generics_Rhino Mocks - Fatal编程技术网

C# Rhino Mocks:如何存根泛型方法以捕获匿名类型?

C# Rhino Mocks:如何存根泛型方法以捕获匿名类型?,c#,unit-testing,generics,rhino-mocks,C#,Unit Testing,Generics,Rhino Mocks,我们需要存根一个将使用匿名类型作为类型参数调用的泛型方法。考虑: 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&

我们需要存根一个将使用匿名类型作为类型参数调用的泛型方法。考虑:

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);
接口IProgressReporter
{
T报告(T progressUpdater);
}
//单元测试安排:
Func returnArg=(x=>x);//我们希望回复这个论点
_reporter.Stub(x=>x.Report(null).IgnoreArguments().Do(returnArg);
如果在被测方法中对.Report()的实际调用是以object作为类型参数完成的,那么这将起作用,但实际上,调用该方法时T是匿名类型。在被测方法之外,此类型不可用。因此,从未调用存根


是否可以在不指定类型参数的情况下存根泛型方法?

我不清楚您的用例,但您可以使用帮助器方法为每个测试设置存根。我没有Rhinomock,因此无法验证这是否有效

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);
}
private void HelperMethod()
{
Func returnArg=(x=>x);//如果需要,也可以使用T代替object
_reporter.Stub(x=>x.Report(null)).IgnoreArguments().Do(returnArg);
}
然后在你的测试中:

public void MyTest()
{
   HelperMethod<yourtype>();
   // rest of your test code
}
public void MyTest()
{
HelperMethod();
//其余的测试代码
}

回答您的问题:不,在不知道Rhino的泛型参数的情况下,不可能存根泛型方法。泛型参数是Rhino中方法签名的重要部分,并且没有“任何”

在您的情况下,最简单的方法就是编写一个手工编写的模拟类,它提供了
IProgressReporter
的虚拟实现

class ProgressReporterMock : IProgressReporter
{
    T Report<T>(T progressUpdater)
    {
      return progressUpdater;
    }
}
class ProgressReporterMock:IProgressReporter
{
T报告(T progressUpdater)
{
返回进程更新程序;
}
}

有一点,但是被调用方是如何使用匿名类型对象的?我从来没有见过这样的用例。在这里试着回顾一下泛型方法的选择。。好问题;)重点不是Report方法对参数做任何处理,而是返回它。它促进了LINQ表达式中的链接。因此,我们当然可以重写它,但我想我们可以试一试。如果创建另一个具有相同顺序和属性类型的匿名类型,则它们应为相同类型。也许这对你有帮助。。在测试中创建一个类似的虚拟类型,并对其执行GetType()以检索该类型。。。但是就像我之前说的。。看起来很复杂/聪明。简单是首选:)@Gishu-嘿,这很有趣。它会有相同的类型吗?我一定会仔细看看的.确认。。见备注部分-第2段