嘲讽泛型方法调用任何给定的类型参数 [英] Mocking generic method call for any given type parameter
问题描述
我有一个接口
public interface IDataProvider
{
T GetDataDocument<T>(Guid document) where T:class, new()
}
我想嘲笑它在某种程度上,这将只返回给定类型的新实例,无论确切类型的,是这样的:
I'd like to mock it in a way, that it would just return a new instance of a given type, regardless of the exact type, something like:
myMock.Setup(m => m.GetDataDocument<It.IsAny<Type>()>(It.IsAny<Guid>()))
.Returns(() => new T());
(不,当然工作,因为我不能给任何类型的参数,起订量,和我不知道必须返回哪种类型。
(which doesn't work of course, because I cannot just give any type parameter to moq, and I can't know which type must be returned.
在这一个任何想法?
推荐答案
而不是使用一个模拟的,也许你的情况会更好使用的存根
Instead of using a mock, maybe your case would be better to use a Stub.
public class StubDataProvider : IDataProvider
{
public T GetDataDocument<T>(Guid document) where T : class, new()
{
return new T();
}
}
如果你真的需要一个模拟的(所以你可以验证 GetDataDocument
被称为),而不是试图用嘲讽的框架有时更容易只需创建一个模拟类出正确的搏斗。
If you truly need a mock (so you can verify that GetDataDocument
was called). Instead of trying to wrestle with a Mocking framework it sometimes is easier to just create a Mock class out right.
public class MockDataProvider : IDataProvider
{
private readonly Action _action;
public MockDataProvider(Action action)
{
_action = action;
}
public T GetDataDocument<T>(Guid document) where T : class, new()
{
_action();
return new T();
}
}
和比你的测试:
bool wasCalled = false;
IDataProvider dataProvider = new MockDataProvider(() => { wasCalled = true; });
var aTable = dataProvider.GetDataDocument<ATable>(new Guid());
Debug.Assert(wasCalled);
这篇关于嘲讽泛型方法调用任何给定的类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!