简体   繁体   English

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

[英]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:这是我对MyService class 的DoWork方法的测试:

  • Create a new mock object of the child interface新建一个子接口的mock object
  • Setup the GetParent method of the parent interface设置父接口的GetParent方法
  • Pass the mock object to the service constructor将模拟 object 传递给服务构造函数
  • Execute the DoWork执行 DoWork
  • Expect to have the resp = "It really works with something!"期望有resp =“它真的适用于某些东西!” but it's null但它是 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起订量 4.16.1
  • .NET CORE (.NET 5) .NET 核心 (.NET 5)
  • XUnit 2.4.1 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>() .您的模拟设置说要模拟传入"something"的方法。您应该更改它以匹配 class 传入的内容,例如"it works"或更容易的是允许使用It.IsAny<string>()的任何字符串It.IsAny<string>() For example:例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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