❔ 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:
Any ideas how can I implement testing method UpdateAsync_ReturnsUpdatedOrderItem_WhenOrderItemExists()?
Much appreciated in advance!
7 Replies
I have also tried out using AnyAsync in order to mock ContainsAsync in my DbSet setup, but it's also an extension method:
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
yeah, I have been looking through this one
Here I am not mocking any of extension methods, and due to this reason the test fails and returns null. Basically, need to mock ContainsAsync here, and the test will succeed.
Pretty tough question, I guess I will just use an in-memory database testing method for all my repositories.
Don't
Use the same database engine
https://dotnet.testcontainers.org/ is great for spinning that up if it's not something like sqlite
you cant directly mock extensions
yeah that's what I literally mentioned
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.