Setting up returns with generic parameters

独自空忆成欢 提交于 2020-08-09 14:55:26

问题


So using Moq to try and do unit tests, I have something like this method I'm trying to mock:

Task<S> UseFooAsync<S>(Func<T, S> func);

And I can set it up, for a specific case, like this:

data.Setup(r => r.UseFooAsync(It.IsAny<Func<DB, MyBar>>()))
    .Returns(Func<DB, MyBar> f => Task.FromResult(f(myMockObj.Object));

For the case where I specify all the generic type parameters. And I can confirm it works because in my test I can do:

myMockObj.Verify(m => m.SomeFunction(), Times.Once);

Which will verify that the function that I supplied my mock myMockObj to tried to call a function on that object.

But I'd like to make it more generic. So I tried this:

data.Setup(r => r.UseFooAsync(It.IsAny<Func<DB, It.IsAnyType>>()))
    .Returns((Func<DB, It.IsAnyType> f) => Task.FromResult(f(myMockObj.Object)));

And this compiles just fine, but in my test, it seems to not get the myMockObj so my verify fails. Does anybody know why? Is it possible to make this work generically? Or am I resigned to having to setup for each generic parameter type I need to mock for the purpose of my unit test(s)?

来源:https://stackoverflow.com/questions/61753375/setting-up-returns-with-generic-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!