我创建了单元测试,并且必须模拟我的EF的context
。我使用Moq
库和Xunit
。我有这样的测试方法:
[Fact]
public async Task DeleteAttachmentCommandHandler_WithValidCommand_ShouldCallSaveChangesAsyncOnce()
{
var command = new DeleteAttachmentCommand { Id = Guid.NewGuid() };
var attachments = new List<Attachment>();
var dbSetMock = attachments.AsQueryable().BuildMockDbSetForAsyncQueryOperations();
_context.Setup(x => x.Set<Attachment>()).Returns(dbSetMock.Object);
_context.Setup(x => x.SaveChangesAsync(It.IsAny<CancellationToken>())).ReturnsAsync(1).Verifiable();
await Act(command);
_context.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
_context
的类型为Mock<IEmployeeSettlementsDbContext>
BuildMockDbSetForAsyncQueryOperations
是我的扩展方法,这要归功于MSDN文档-> https://docs.microsoft.com/en-us/ef/ef6/fundamentals/testing/mocking,它使用了TestDbAsyncEnumerable
,TestDbAsyncEnumerator
,TestDbAsyncQueryProvider
之类的异步提供程序。我的扩展名BuildMockDbSetForAsyncQueryOperations
如下所示:
public static Mock<IDbSet<TEntity>> BuildMockDbSetForAsyncQueryOperations<TEntity>(this IQueryable<TEntity> data) where TEntity : class
{
var dbSetMock = new Mock<IDbSet<TEntity>>();
dbSetMock.As<IDbAsyncEnumerable<TEntity>>().Setup(x => x.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator<TEntity>(data.GetEnumerator()));
dbSetMock.As<IQueryable<TEntity>>().Setup(x => x.Provider).Returns(new TestDbAsyncQueryProvider<TEntity>(data.Provider));
dbSetMock.As<IQueryable<TEntity>>().Setup(x => x.Expression).Returns(data.Expression);
dbSetMock.As<IQueryable<TEntity>>().Setup(x => x.ElementType).Returns(data.ElementType);
dbSetMock.As<IQueryable<TEntity>>().Setup(x => x.GetEnumerator()).Returns(data.GetEnumerator());
return dbSetMock;
}
在测试的实际处理程序方法中,我有一行:
var attachment = await _context.Set<Attachment>()
.SingleAsync(x => x.Id == command.Id);
当我运行测试时,它失败并显示消息
消息:System.InvalidOperationException:该序列不包含匹配的元素。
但是,当我将处理程序中的查询更改为ListAsync()
而不是SingleAsync()
时,则模拟程序已正确设置,并向我返回了一个空列表。但这不适用于使用SingleAsync()
的单个元素。
编辑: 这是我完整的Handler方法:
public async Task<Unit> Handle(DeleteAttachmentCommand command, CancellationToken cancellationToke = default(CancellationToken))
{
ValidateCommand(command);
var attachment = await _context.Set<Attachment>().SingleAsync(x => x.Id == command.Id);
attachment.IsDeleted = true;
await _context.SaveChangesAsync();
return Unit.Value;
}