我正在尝试在异步调用上使用Moq(4.10),但是我无法掌握它。
搜索如何执行此操作,找到我尝试过的答案,但无法使其正常工作。
这是我的考验
public class Test
{
[Fact]
public void Test_Create()
{
var repositoryMock = new Mock<IRepository>();
repositoryMock
.Setup(repo => repo.CreateAsync(It.IsAny<Aggregate >()))
.Returns(Task.CompletedTask);
/// also tried this
/// => .Returns(Task.FromResult(default(object)))
/// and
/// => .Returns(Task.FromResult(false)));
var useCase = new CreateUseCase(repositoryMock.Object);
Task.Run(async () => { await useCase.HandleAsync(new CreateRequest()); });
repositoryMock.VerifyAll();
}
}
资源
How can I tell Moq to return a Task?
得到这个例外
Moq.MockException:'以下关于模拟的设置
'Mock '不匹配:IRepository
repo => repo.CreateAsync(It.IsAny ())
回购看起来像这样
public interface IRepository
{
Task CreateAsync(Aggregate aggregate);
}
用例
public class CreateUseCase : IUseCaseHandler<CreatRequest>
{
private IRepository _repository;
public CreateUseCase (IRepository repository)
{
_repository= repository?? throw new System.ArgumentNullException(nameof(repository));
}
public async Task HandleAsync(CreateRequest request, CancellationToken? cancellationToken = null)
{
Aggregate aggregate = new Aggregate();
aggregate.Create();
await _repository.CreateAsync(aggregate);
}
}
仓库
public sealed class OrderRepository : ProxyRepository<OrderAggregate>, IOrderRepository
{
public OrderRepository(IUnitOfWork unitOfWork, INotificationDispatcher eventHandler)
: base(unitOfWork, eventHandler)
{
}
async Task IRepository.CreateAsync(Aggregate aggregate)
{
await base.AddAsync(aggregate);
}
}
我做错了什么或想念什么?
最佳答案
除非我在您的问题中遗漏某些东西,否则我们通常不必模拟不会返回任何值的接口方法。
public class CreateUseCaseTests
{
[Fact]
public async Task HandleAsync_ShouldCreateRequest()
{
// Arrange
var repositoryMock = new Mock<IRepository>();
var sut = new CreateUseCase(repositoryMock.Object);
// Act
await sut.HandleAsync(new CreateRequest());
// Assert
repositoryMock.Verify(x => x.CreateAsync(It.IsAny<Aggregate>()), Times.Once);
}
}
关于c# - 尝试测试Task时获得Moq异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53174267/