Unit testing MongoDB in C# part 2: the database context
Unit testing MongoDB in C# part 2: the database context

Unit testing MongoDB in C# part 2: the database context

2015, Dec 20    

Hi All!

Last time I rambled a little bit about TDD and how to implement a very simple MongoDB repository.

This time I want to introduce you to my cool friend, DbContext. The basic idea is to have an interface exposing all the collection on your db, or, in our case, all the repositories. Take a look at this:

</table> </div></p> </div> </div> </div>
view raw
IDbContext
hosted with ❤ by GitHub
</p> </div> </div> ( I will leave to you the definition of the entities ). The implementation is pretty straightforward:
public interface IDbContext
{
IRepositoryPosts { get; } </td> </tr>
IRepositoryUsers { get; } </td> </tr>
IRepositoryTags { get; } </td> </tr>
IRepositoryTaxonomies { get; } </td> </tr>
}
public class DbContext : IDbContext
{
public DbContext(IRepositoryFactory repoFactory, string connectionString, string dbName)
{
if (string.IsNullOrWhiteSpace(connectionString))
throw new ArgumentNullException("connectionString");
if (string.IsNullOrWhiteSpace(dbName))
throw new ArgumentNullException("dbName");
this.Posts = repoFactory.Create<Entities.Video>(new RepositoryOptions(connectionString, dbName, "posts"));
this.Users = repoFactory.Create<Entities.User>(new RepositoryOptions(connectionString, dbName,"users") );
this.Tags = repoFactory.Create<Entities.Tag>(new RepositoryOptions(connectionString, dbName, "tags"));
this.Taxonomies = repoFactory.Create<Entities.Taxonomy>(new RepositoryOptions(connectionString, dbName, "taxonomies"));
}
public IRepository<Entities.Post> Posts { get; private set; }
public IRepository<Entities.User> Users { get; private set; }
public IRepository<Entities.Tag> Tags { get; private set; }
public IRepository<Entities.Taxonomy> Taxonomies { get; private set; }
}
</p>
view raw
DbContext.cs
hosted with ❤ by GitHub
</p>
A couple of details worth noting here: 1) the repositories are exposed as interfaces and not as specific implementation, making tests easier to write 2) again, all the repositories are generated via a factory, injected directly in the ctor. The Factory Pattern allows us to add more repositories without much hassle and, moreover, to inject a “fake” factory during our tests. [Next time](http://www.davidguida.net/unit-testing-mongodb-in-c-part-3-the-database-factories/) we’ll discuss about how to implement a factory for our repo-needs 🙂

Did you like this post? Then