gpt4 book ai didi

c# - 尝试测试任务时 Moq 出现异常

转载 作者:行者123 更新时间:2023-11-28 21:07:29 30 4
gpt4 key购买 nike

我正在尝试在异步调用中使用 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: 'The following setups on mock 'Mock<.Repository.IRepository:00000001>' were not matched: IRepository repo => repo.CreateAsync(It.IsAny < Aggregate>())

repo 看起来像这样

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);
}
}

我做错了什么或遗漏了什么?

最佳答案

我们通常不必模拟不返回任何接口(interface)的方法,除非我在您的问题中遗漏了某些内容。

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# - 尝试测试任务时 Moq 出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53174267/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com