[英]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方法的测试:
[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:其他信息:
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.