How do you Setup a generic returntype in Moq?
I have the following interface:
public interface IFoo
{
T Bar<T>();
}
Now I want to setup Bar<T>() to work inside a test
var foo = new Mock<IFoo>();
foo.Setup(x => x.Bar<It.IsAnyType>()).Returns(new Mock<???>().Object);
How do I fill out ???, or if that is not possible, then how do I return a generic mock?
There are 100s of types, I am trying to avoid mocking them all. The test breaks (because the code throws and exception) if the call returns null for any type, which is sadly the default non-mocked behavior.
If T is a reference type ie
public interface IFoo {
T Bar<T>() where T : class;
}
Then it would be easier to just create a slim mock
public class MockFoo : IFoo {
private MockFoo() {
}
public T Bar<T>() where T : class => Mock.Of<T>();
public static IFoo New() => new MockFoo();
}
which can be initialized while arranging the test and using MOQ for mocking the output of Bar
//Arrange
IFoo foo = MockFoo.New();
//...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With