使用 Moq 模拟时模拟 returns null
Mock returns null when mocking using Moq
我可能遗漏了一些明显的东西。使用 Asp.Net 核心后台服务。简化设置如下:
SUT
public class OrderService: BaseOrderService
{
IConsumer<string, string> _consumer;
public OrderService(IBuilder consumerBuilder, ILogger logger) : base(logger)
{
_consumer = consumerBuilder.Build(() => Provider);
}
}
public abstract class BaseOrderService: BackgroundService
{
protected BaseOrderService(ILogger logger){}
....
....
}
IBuilder
public interface IBuilder
{
IConsumer<string, string> Build(Func<string> providerFunc);
}
单元测试
[Fact]
public async Task TestDescription()
{
var mockBuilder = new Mock<IBuilder>();
var mockConsumer = new Mock<IConsumer<string, string>>();
mockBuilder.Setup(x => x.Build(It.IsAny<string>)).Returns(mockConsumer.Object);
var sut = new OrderService(mockBuilder.Object, NullLogger.Instance);
await sut.StartAsync(default);
....
....
}
问题
- 根据 运行 我的测试,在 OrderService 构造函数中调用
_consumer = _consumerBuilder.Build(()=> Provider)
returns null,尽管我已经在中提供了模拟设置测试。
我错过了什么?任何指针将不胜感激。
使用了错误的参数匹配器。
被嘲笑的成员期望Func<string>
IConsumer<string, string> Build(Func<string> providerFunc);
但是你的代码设置 It.IsAny<string>
mockBuilder
.Setup(x => x.Build(It.IsAny<string>)) //<-- WRONG
.Returns(mockConsumer.Object);
应该是It.IsAny<Func<string>>()
mockBuilder
.Setup(x => x.Build(It.IsAny<Func<string>>())) //<--
.Returns(mockConsumer.Object);
我可能遗漏了一些明显的东西。使用 Asp.Net 核心后台服务。简化设置如下:
SUT
public class OrderService: BaseOrderService
{
IConsumer<string, string> _consumer;
public OrderService(IBuilder consumerBuilder, ILogger logger) : base(logger)
{
_consumer = consumerBuilder.Build(() => Provider);
}
}
public abstract class BaseOrderService: BackgroundService
{
protected BaseOrderService(ILogger logger){}
....
....
}
IBuilder
public interface IBuilder
{
IConsumer<string, string> Build(Func<string> providerFunc);
}
单元测试
[Fact]
public async Task TestDescription()
{
var mockBuilder = new Mock<IBuilder>();
var mockConsumer = new Mock<IConsumer<string, string>>();
mockBuilder.Setup(x => x.Build(It.IsAny<string>)).Returns(mockConsumer.Object);
var sut = new OrderService(mockBuilder.Object, NullLogger.Instance);
await sut.StartAsync(default);
....
....
}
问题
- 根据 运行 我的测试,在 OrderService 构造函数中调用
_consumer = _consumerBuilder.Build(()=> Provider)
returns null,尽管我已经在中提供了模拟设置测试。
我错过了什么?任何指针将不胜感激。
使用了错误的参数匹配器。
被嘲笑的成员期望Func<string>
IConsumer<string, string> Build(Func<string> providerFunc);
但是你的代码设置 It.IsAny<string>
mockBuilder
.Setup(x => x.Build(It.IsAny<string>)) //<-- WRONG
.Returns(mockConsumer.Object);
应该是It.IsAny<Func<string>>()
mockBuilder
.Setup(x => x.Build(It.IsAny<Func<string>>())) //<--
.Returns(mockConsumer.Object);