Moq – How to implement mock for method of generic base class?

I have the following interfaces and service implemented like this:

public interface IParentInterface<T> where T : class
{
    T GetParent(T something);
}

public interface IChildInterface : IParentInterface<string>
{
    string GetChild();
}

public class MyService
{
    private readonly IChildInterface _childInterface;

    public MyService(IChildInterface childInterface)
    {
        _childInterface = childInterface;
    }

    public string DoWork()
    {
        return _childInterface.GetParent("it works");
    }
}

Here is my test for the DoWork method of MyService class:

  • Create a new mock object of the child interface
  • Setup the GetParent method of the parent interface
  • Pass the mock object to the service constructor
  • Execute the DoWork
  • Expect to have the resp = “It really works with something!” but it’s null
[Fact]
public void Test1()
{
    var mockInterface = new Mock<IChildInterface>();
    mockInterface
        .As<IParentInterface<string>>()
        .Setup(r => r.GetParent("something"))
        .Returns("It really works with something!");

    var service = new MyService(mockInterface.Object);

    string resp = service.DoWork(); // expects resp = "It really works with something!" but it's null

    Assert.NotNull(resp);
}

Other info:

  • Moq 4.16.1
  • .NET CORE (.NET 5)
  • XUnit 2.4.1

Answer

Your mock setup is saying to mock the method with "something" is passed in. You should change that to match what the class is passing in, e.g. "it works" or much easier is to allow any string using It.IsAny<string>(). For example:

mockInterface
    .As<IParentInterface<string>>()
    .Setup(r => r.GetParent(It.IsAny<string>()))
    .Returns("It really works with something!");

Leave a Reply

Your email address will not be published. Required fields are marked *