[英]Is it possible to use Rhino Mocks to stub a generic method where I don't care about the type?
[英]Rhino Mocks: How to stub a generic method to catch an anonymous 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<T>() 的实际调用是使用 object 作为类型参数完成的,这将起作用,但实际上,该方法是使用 T 作为匿名类型调用的。 此类型在被测方法之外不可用。 因此,永远不会调用存根。
是否可以在不指定类型参数的情况下对泛型方法进行存根?
我不清楚您的用例,但您可以使用辅助方法为每个测试设置存根。 我没有 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 的通用 arguments 的情况下,不可能存根通用方法。 通用的 arguments 是 Rhino 中方法签名的重要组成部分,并且没有“任何”。
在您的情况下,最简单的方法是编写一个手写的模拟 class,它提供了IProgressReporter
的虚拟实现。
class ProgressReporterMock : IProgressReporter
{
T Report<T>(T progressUpdater)
{
return progressUpdater;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.