Unit testing MongoDB in C# part 1: the repository
Unit testing MongoDB in C# part 1: the repository

Unit testing MongoDB in C# part 1: the repository

2015, Dec 17    

Ok folks, this time I’ll talk/brag a little bit about the fabulous C# MongoDB driver and how you can write some testable code with it.

If you have come across this post, probably you already know what unit tests and TDD are so you can go directly to the code.

For those of you that have lived under a rock for the last 15 years or so, here are the words of a very wise man.

Take your time, I will be here.

 

 

 

Interesting concept, isn’t it?

Just because I like adding links to my posts, the amazing uncle Bob has a nice list of the “three rules” of TDD.

Although there might be cases where TDD is not advisable, or where is basically useless, it’s an essential tool that every developer needs to have at his disposal… so let’s get started!

The basic idea is to have an interface for everything. Yes, simple as that. DI at it’s finest, kids! Always remember to separate your concerns, avoiding  huge monolithic classes that do too much. Divide et impera.

We can start with this:

public interface IRepository<TEntity>
{
string CollectionName { get; }
Task<long> CountAsync(FilterDefinition<TEntity> filter);
IFindFluent<TEntity, TEntity> Find(FilterDefinition<TEntity> filter);
IFindFluent<TEntity, TEntity> Find(Expression<Func<TEntity, bool>> filter);
Task<TEntity> FindOneAndReplaceAsync(FilterDefinition<TEntity> filter, TEntity replacement);
Task<TEntity> FindOneAndReplaceAsync(Expression<Func<TEntity, bool>> filter, TEntity replacement);
}
</p>
view raw
IRepository.cs
hosted with ❤ by GitHub
</p>

Small and easy. Just basic read and update operations, nothing else. You can find a sample implementation here, as you can see it’s a simple wrapper over the MongoDB driver, nothing else, but having the interface allows you to hide all the implementation details AND to eventually mock everything in your tests.

Enough for now, the new Star Wars movie is waiting for me !

Next time we’ll talk about factories and how to create a simple database context.

Did you like this post? Then