问题描述
|
我们需要存根一个通用方法,该方法将使用匿名类型作为类型参数来调用。考虑:
()的实际调用是使用object作为类型参数来完成的,那么这实际上是可行的,但是实际上,该方法是在T为匿名类型的情况下调用的。此类型在被测方法之外不可用。结果,该存根永远不会被调用。
是否可以在不指定type参数的情况下存根通用方法?
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 解决方法
目前尚不清楚您的用例,但您可以使用帮助程序方法为每个测试设置存根。我没有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
}
, 要回答您的问题:不,在不知道Rhino通用参数的情况下无法对通用方法进行存根。通用参数是Rhino中方法签名的重要组成部分,没有\“ Any \\”。
在这种情况下,最简单的方法就是编写一个手写的模拟类,该类提供了IProgressReporter
的虚拟实现。
class ProgressReporterMock : IProgressReporter
{
T Report<T>(T progressUpdater)
{
return progressUpdater;
}
}