plam
plam
CC#
Created by plam on 3/8/2023 in #help
❔ Mocking EF Core extensions methods.
I have actually tried a lot of stuff just in order to mock one of the methods which are used by Repository. Specifically, the issue is connected to using ContainsAsync. Since it's an extension method, I'm not able to mock it directly. I have tried using Wrapper pattern, especially wrapping DbSet and the ContainsAsync method itself. Furthermore, I have tried to implement it via using custom IAsyncEnumerator in addition to AsyncQueryProvider. I have also checked out two different libraries which do allow to mock stuff easier: MockQueryable.Moq & Moq.EntityFrameworkCore. Both of them didn't provide me with a proper result. Here's my repository method:
public async Task<OrderItem?> UpdateAsync(OrderItem orderItem, CancellationToken cancellationToken = default)
{
bool isContains = await _dbContext.OrderItems.ContainsAsync(orderItem, cancellationToken);
if (!isContains)
{
return null;
}

_dbContext.OrderItems.Update(orderItem);
await _dbContext.SaveChangesAsync(cancellationToken);

return orderItem;
}
public async Task<OrderItem?> UpdateAsync(OrderItem orderItem, CancellationToken cancellationToken = default)
{
bool isContains = await _dbContext.OrderItems.ContainsAsync(orderItem, cancellationToken);
if (!isContains)
{
return null;
}

_dbContext.OrderItems.Update(orderItem);
await _dbContext.SaveChangesAsync(cancellationToken);

return orderItem;
}
Any ideas how can I implement testing method UpdateAsync_ReturnsUpdatedOrderItem_WhenOrderItemExists()? Much appreciated in advance!
11 replies