Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq - Setup Generic Return type

Tags:

c#

.net

moq

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.

like image 483
Martin Jespersen Avatar asked Oct 24 '25 14:10

Martin Jespersen


1 Answers

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();

//...
like image 177
Nkosi Avatar answered Oct 26 '25 04:10

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!