CategoryUnit Testing

Unit testing MongoDB in C# part 4: the tests, finally

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 an 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.

 

CQRS: on Commands and Validation

Let’s have a quick discussion about CQRS. There’s a lot to say to be honest, so let’s try to focus on just one thing today: validating your Commands (who knows, I could start a series after this, we’ll see).

The idea is simple: how can I make sure that the data I am passing to my Command Handler is valid?

Also, what is the definition of “valid” ?

There are several aspect to take in consideration, several “levels” of validation. I could just make sure the Command object is not null and/or the data it contains is not empty. Or I could run the validation against some kind of context and check the application Business Rules.

As you can imagine, having different levels means that we could have different implementations scattered in various places/layers of our architecture. For example I could have the API Controller (or whatever outmost layer you have) check for null and perform some Business Context validation later, before or directly in the Command Handler.

In my last project however, I decided to keep things simple and keep my validation in just one place.

Initially the right spot was the Command Handler itself, but of course this would have violated the SRP.

A quick and immediate solution was to have a separate instance of a IValidator<TCommand> injected in the handler. Easy.

Then I realised that my handlers are more “close to the metal” than expected: in most of the cases they access directly the DAL (passing through some kind of IDbContext) and I didn’t wanted to rewrite the call to the IValidator in case I had to switch the persistence layer.

Luckily enough, there’s a nice pattern that came into rescue: the Decorator! As explained very clearly on the SimpleInjector docs, you can create a ValidationCommandHandlerDecorator class, inject an IValidator<TCommand> and let your IoC do the rest.

Maaaaagic.

Bonus tip: in some cases you may want to skip completely the validation. Maybe you have a very good reason or maybe you’re just lazy. Whatever.

In this case, all you have to do is to write some kind of NullValidator<TCommand> class and instruct your IoC to use it when a specific validator is missing for that Command.

Unit testing MongoDB in C# part 3: the database factories

Welcome to the third article of the series!

Last time I was talking about the database context and at how I injected a Factory to create the repositories. Of course we could have injected every single repository in the cTor, but this way adding a new collection to the database would force too many changes.

Injecting just the factory instead allows us to create internally all the repositories we need, add new ones easily and of course makes our life easier when it comes to testing.

Let’s take a look at our Repository Factory interface:

as you can see, that’s very standard and easy. The implementation also is pretty straightforward:

A couple of notes on this:

  1. the RepositoryOptions class is just a simple Value Object encapsulating some details like the connection string and the name of the collection
  2. in the cTor we have a dependency on another Factory used to get a reference to the database. Why we do this? I guess you know the answer 😀

As you can see, this injected Factory also is very easy:

you can find the implementation here.

Next time: let’s write some tests!

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

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:

( I will leave to you the definition of the entities ). The implementation is pretty straightforward:

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 we’ll discuss about how to implement a factory for our repo-needs 🙂

Unit testing MongoDB in C# part 1: the repository

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:

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.

© 2017 Davide Guida

Theme by Anders NorenUp ↑