More than a year. Wow, that’s a lot, even for me! In the last episode of this series, we discussed about how to create the Factories for our Repositories. I guess now it’s time to put a use to all those interfaces and finally see how to unit test our MongoDB repositories 🙂
Remember: we are not testing the driver here. The MongoDB team is responsible for that. Not us.
What we have to do instead is to make sure all our classes follow the SOLID principles and are testable. This way we can create a fake implementation of the low-level data access layer and inject it in the classes we have to test. Stop.
Let’s have a look at the code:
In our little example here I am testing a CQRS Command Handler, the one responsible for creating a user. Our handler has an IDbContext as dependency, which being an interface allows us to use the Moq Nuget package to create a fake context implementation.
Also, we have to instruct the mockDbContext instance to return a mock User Repository every time we access the .Users property.
At this point, all we have to do is to create the sut, execute the method we want to test, and Verify() our expectations.
Let’s make a more interesting example now:
Now that we have created the user, we may want also to update some of his details. The idea here is to instruct the mockRepo instance to return a specific user every time the FinstOneAsync method is executed.
Again, now we just need to verify the expectations and we’re done!
Note that in this case, we are making an assumption about the inner mechanism of the Handle() method of the UpdateUserHandler class. Personally I tend to stick with Black Box Testing, but sometimes (eg. now) you might be forced to use White Box Testing instead. If you don’t know what I am talking about, there’s a nice article here you may want to read.
I’ve added another article, which can be considered as the final missing piece to this Series. Unit tests are fine, but when it comes to connecting the parts, we’re talking of “Integration tests” instead.