Using AutoMoq methods with generic signatures
Asked Answered
H

1

3

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?

Heptangular answered 20/10, 2015 at 23:18 Comment(0)
D
6

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);
Dierdredieresis answered 21/10, 2015 at 0:43 Comment(1)
Right, I should have noted I way using AutoConfiguredMoqCustomizations. But thanks for confirming that AutoConfiguredMoqCustomizations can't configure generic methods. So it looks like I can't avoid doing some level of setup, but I could at least avoid having to set up the return values by using ReturnsUsingFixture. I'll try that out. Thanks.Heptangular

© 2022 - 2024 — McMap. All rights reserved.