Using AutoMoq methods with generic signatures

拟墨画扇 提交于 2019-12-02 05:29:58

问题


I'm currently using a test framework I've thrown together using xUnit, AutoMoq, AutoFixture, and AutoFixture.XUnit2. I'm running into issues with mocking methods with generic signatures.

AutoFixture seems to handle generic items just fine. If I ask for a CustomeObject<Task<List<Task<string>>>>, or some other ridiculous nested generic type, it seems to generate them as expected all the way down to the last node.

However, if I have an interface like this:

public interface ITestInterface{
    T Get<T>();
}

and then try to call the method from the mock I got from AutoMoq it just returns null. So, for example:

[Theory]
[MyAutoDaqaAttribute]
public async Task ATest(
    Mock<ITestInterface> service
) {
    var result = service.Object.Get<string>();
}

In this code result will be null. That seems odd to me. Shouldn't it go to autofixture and try to create a value of type T i.e. a new string? It seems like Autofixture has already shown that it can handle generics just fine.

Or do you always just have to manually setup any mock method that has a generic in its signature?


回答1:


Mocked objects don't go through AutoFixture by default. You can use the AutoConfiguredMoqCustomization for that though.

However, in your case, the method is generic. AutoConfiguredMoqCustomization doesn't work with generic methods, you'll have to manually set up the method.

Extracted from here:

AutoConfiguredMoqCustomization does not configure generic methods either. You can, however, easily set these up using the ReturnsUsingFixture extension method:

converter.Setup(x => x.Convert<double>("10.0"))
         .ReturnsUsingFixture(fixture);


来源:https://stackoverflow.com/questions/33248438/using-automoq-methods-with-generic-signatures

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