I am trying to do tdd and use mongodb as database. But i cant resolve problem of mocking mongodb. Is there any ability to mock mongodb for unit testing in .NET?
Update
I found very good soltion reading blog.
You can find it here:
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Instead of mocking MongoDB, you should be mocking a layer on top of MongoDB.
You might want to consider an interface that exposes the operations on your repository which are agnostic to the underlying data store. For example, you might want an interface that abstracts out operations on
Studenttypes, like so:When you create your other dependencies, you inject instances of the above interface, or whichever higher-level abstractions you choose.
The point is, don’t expose MongoDB directly.
Once you do that, you can mock the interfaces you create all you want, having one implementation for testing against the mock implementation, and then an actual implementation with it’s own tests to validate that operations on the implementation are correct when the underlying implementation is with MongoDB.
While it’s definitely possible to mock most of MongoDB’s classes (as the methods are
virtual), you gain the benefit of being persistence agnostic; if you want to switch to say, CouchDB or elasticsearch, you don’t have to change the calls to these interfaces, you simply create a new implementation.Because you are trying to test the implementation of the repository, then you are generally fine, as has been stated before, most of MongoDB’s functions are
virtual, which is friendly to most mocking libraries.That said, you’ll have to make sure that you pass the
MongoDatabaseinto your repository (not create it in the repository) so that in your unit tests, you can create the appropriate mock and then pass it into your repository implementation for testing.