Rhino Mocks:如何存根用于捕获匿名类型的泛型方法?

Tor*_*gen 11 c# generics unit-testing 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<object>(null).IgnoreArguments().Do(returnArg);
Run Code Online (Sandbox Code Playgroud)

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

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

Ind*_*lta 5

我不清楚您的用例,但您可以使用帮助程序方法为每个测试设置存根。我没有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);
}
Run Code Online (Sandbox Code Playgroud)

然后在您的测试中执行以下操作:

public void MyTest()
{
   HelperMethod<yourtype>();
   // rest of your test code
}
Run Code Online (Sandbox Code Playgroud)