Moq - 如何为通用基类的方法实现模拟?

kal*_*kal 2 c# interface moq mocking

我有以下接口和服务,如下所示:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我对MyService类的DoWork方法的测试:

  • 创建子界面的新模拟对象
  • 设置父接口的GetParent方法
  • 将模拟对象传递给服务构造函数
  • 执行DoWork
  • 期望得到resp =“它确实可以与某些东西配合使用!” 但它是空的
[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);
}
Run Code Online (Sandbox Code Playgroud)

其他信息:

  • 起订量 4.16.1
  • .NET 核心 (.NET 5)
  • XUnit 2.4.1

Dav*_*idG 5

您的模拟设置表示要模拟"something"传入的方法。您应该更改它以匹配传入的类,例如"it works",或者更简单的是允许任何字符串使用It.IsAny<string>(). 例如:

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