Moq - 如何为通用基础 class 的方法实现模拟?
Moq - How to implement mock for method of generic base class?
我有如下实现的接口和服务:
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 方法的测试 class:
- 创建子接口的新模拟对象
- 设置父接口的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);
}
其他信息:
- 起订量 4.16.1
- .NET 核心 (.NET 5)
- XUnit 2.4.1
你的模拟设置是说模拟传入 "something"
的方法。你应该改变它以匹配 class 传入的内容,例如"it works"
或更简单的方法是允许使用 It.IsAny<string>()
的任何字符串。例如:
mockInterface
.As<IParentInterface<string>>()
.Setup(r => r.GetParent(It.IsAny<string>()))
.Returns("It really works with something!");
我有如下实现的接口和服务:
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 方法的测试 class:
- 创建子接口的新模拟对象
- 设置父接口的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);
}
其他信息:
- 起订量 4.16.1
- .NET 核心 (.NET 5)
- XUnit 2.4.1
你的模拟设置是说模拟传入 "something"
的方法。你应该改变它以匹配 class 传入的内容,例如"it works"
或更简单的方法是允许使用 It.IsAny<string>()
的任何字符串。例如:
mockInterface
.As<IParentInterface<string>>()
.Setup(r => r.GetParent(It.IsAny<string>()))
.Returns("It really works with something!");