© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
10 replies
daniel

❔ 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!
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

abstract methods inside EF core queries
C#CC# / help
11mo ago
EF Core
C#CC# / help
2y ago
Ef core help
C#CC# / help
10mo ago
✅ EF Core Relationship
C#CC# / help
2y ago