Wilbert Wilbert - 1 month ago 29
C# Question

Mocking generic methods in Moq without specifying T

I have an interface with a method as follows:

public interface IRepo
{
IA<T> Reserve<T>();
}


I would like to mock the class that contains this method without having to specify Setup methods for every type it could be used for. Ideally, I'd just like it to return a
new mock<T>.Object
.

How do I achieve this?

It seems my explanation was unclear. Here's an example - this is possible right now, when I specify the T (here, string):

[TestMethod]
public void ExampleTest()
{
var mock = new Mock<IRepo>();
mock.Setup(pa => pa.Reserve<string>()).Returns(new Mock<IA<string>>().Object);
}


What I would like to achieve is something like this:

[TestMethod]
public void ExampleTest()
{
var mock = new Mock<IRepo>();
mock.Setup(pa => pa.Reserve<T>()).Returns(new Mock<IA<T>>().Object);
// of course T doesn't exist here. But I would like to specify all types
// without having to repeat the .Setup(...) line for each of them.
}


Some methods of the object under test might call reserve for three or four different types. If I have to setup all the types I have to write a lot of setup code for every test. But in a single test, I am not concerned with all of them, I simply need non-null mocked objects except for the one that I am actually testing (and for which I gladly write a more complex setup).

Answer

Unless I'm misunderstand what you need, you could build a method like this:

private Mock<IRepo> MockObject<T>()
{
    var mock = new Mock<IRepo>();
    return mock.Setup(pa => pa.Reserve<T>())
        .Returns(new Mock<IA<T>>().Object).Object;
}
Comments