.net 6 Mongo.Driver
I need to test async methods for mongo, which requires use of IMongoQueryable, but to use methods like FirstOrDefaultAsync, Where, etc, I need to have a valid IMongoQueryable.
Today I need to mock a mongodatabase just to create that for tests and it’s taking a lot of resources and changes on my automation process.
How do I test that?
Hi, @Luiz_Palte,
I understand that you’re attempting to mock parts of the MongoDB .NET/C# Driver. A widely accepted testing practice is “Don’t mock what you don’t own”. In other words, don’t mock third-party dependencies, but only your own abstractions.
The problem with trying to mock the driver is that you must make assumptions about the internal implementation of the driver and the underlying MongoDB cluster. This makes your test suite extremely brittle and unreliable. For example let’s say you do mock IMongoCollection<T>
and all the associated types, but you use a server feature not supported by your current MongoDB version. Your mocked tests would pass - because you’ve made assumptions about return values - but the actual query would fail in production.
I would suggest implementing the Repository Pattern. You could implement IWidgetRepository
, which can be mocked easily because it is an interface that you control. You could then implement a concrete WidgetRepository
, which could then be integration tested (without any mocks). Lastly you could system test your controllers with the concrete implementations to ensure that your entire application works as desired.
Hope this helps.
Sincerely,
James