首页 > 解决方案 > Moq - 如何为通用基类的方法实现模拟?

问题描述

我有如下实现的接口和服务:

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");
    }
}

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

[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);
}

其他信息:

标签: c#interfacemockingmoq

解决方案


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

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

推荐阅读