简体   繁体   中英

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

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, eg "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!");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM