Unit testing MongoDB queries

When writing unit tests, it’s common to stop at the database access layer.
You might have a “dumb” data access layer that just passes stored procedure names and parameters to the SQL database, for instance.
It’s usually very hard to test this layer, since it requires either that your build server has access to a SQL Server instance, or that a SQL Server is running on the build server.
Plus, we’re getting out of unit tests and are entering integration tests, here.

Using a more advanced tool like Entity Framework, in order to test your complex EF queries, there are usually methods to insert fake data into a fake container, like Test Doubles, InMemory, or Effort.

Using MongoDB, you might encounter the same problem : how do I test that my complex queries are working ?

Here for instance, I get the possible colors of a product; how do I know it works using unit tests?

MongoDB has an “inMemory” storage engine, but it’s reserved to the (paid) Enterprise edition. Fortunately, since 3.2, even the Community edition has a not-very-well-documented “ephemeralForTests” storage engine, which loads up an in-memory Mongo instance, and does not store anything on the hard drive (but has poor performances). Exactly what we need!

Before running the data access layer tests, we will need to fire up an in-memory instance of MongoDB.
This instance will be common to all the tests for the layer, otherwise the test runner will fire up new tests faster than the system releases resources (file and ports locks).

You will have to extract the MongoDB binaries in your sources repository somewhere, and copy them besides your binaries on build.

The following wrapper provides a “Query” method that allows us to access the Mongo instance through command-line, bypassing the data access layer, in order to insert test data or query insertion results.

We’re using the IClassFixture  interface of xUnit to fire up a MongoDaemon instance that will be common to all our tests using it.
It means we need to clean up previously inserted test data at each run.

There you have it: a kind-of-easy way to test your Mongo data access layer.

Mocking static methods

I’m working on a pretty old application with no unit tests whatsoever, and I’m trying to write some as I add features and fix bugs.

After successively finding out about MS Fakes, then that it’s only included in VS2012+ Premium/Ultimate and very hard to include in a continuous integration chain, I was pretty stumped until I found this, which works incredibly well.

Another option to transform the static method into a static Func or Action. For instance.

Original code:

You want to “mock” the Add method, but you can’t. Change the above code to this:

Existing client code doesn’t have to change (maybe recompile), but source stays the same.

Now, from the unit-test, to change the behavior of the method, just reassign an in-line function to it:

Put whatever logic you want in the method, or just return some hard-coded value, depending on what you’re trying to do.

This may not necessarily be something you can do each time, but in practice, I found this technique works just fine.

Unit testing custom querystring-based authorization on a WebApi controller

I needed to add a very simple authorization mechanism to my API: use a query string parameter “api_key”, so that it’s compatible with Swagger (using Swashbuckle, there is a field “api_key” in the Swagger UI) and is easily callable through Ruby On Rails.

Following and adapting a nice tutorial, I have done the following.

Implement the authorization filter

Create an interface for your API key “getter”:

Implement this interface; here it’s extremely simple:

Inject this interface through your dependency injector of choice. You don’t have to modify your controllers, which is great.

Then create a filter attribute to use this implementation:

Now you just have to add the [ApiKeyAuthorize] attribute to your controller(s), and you now need to add the proper api_key query string parameter to all your requests.

Test the filter

A few things to test: that your class uses this attribute, and that the attribute does what it says it does.

Test the attribute presence

Here I’m using XUnit and FluentAssertions.
It’s just a matter of listing the attributes on the class, and checking that an attribute matching the one created exists.

Test the attribute inner workings

What are we testing there? That the attribute throws a HttpResponseException when no parameter exists or when the value is wrong, and that it doesn’t throw an exception when it matches.

Setup the tests

Using XUnit and Moq, the test setup looks like this:

The ContextUtil.CreateActionContext method can be picked from the ASP.Net source. The corresponding tests can be found here.

My InjectionSetup.Register is a unit-test-specific injection that allows to use a specific instance instead of creating one, here using LightInject:

Test the attribute

Still using XUnit and FluentAssertions, three simple tests allow to check that the responses are what is expected:

 

Testing Entity Framework layer in database-first mode

In your app, you may have a “query” layer, where all your Linq queries are regrouped. If you don’t, you should. Having your queries inside your controller leads to poor testing and strong coupling.

You will want to test that your queries return what they say they return. In order to do that, you need to mock your Entity Framework entities container.

There is an awesome and complete tutorial here, explaining everything.

If you’re stuck on Visual Studio 2010, you will need to do a few things: first, download and install the ADO.NET DbContext Generator code template, so that your entities use the DbSet type. Then, open your Entity Framework container, right click inside and select “Add a code generation element” (or something like that, my VS is not in english) and select the DbContext elements you just downloaded. You will then be able to customize the way your entities are generated (awesome tool).

In all Visual Studio versions, if you’re not using code-first like the tutorial, you will have to modify the template generation to mark your entities list as virtual (so that they can be mocked). Open your xxx.Context.tt file, find the line with DbSet<<#=Code.Escape(entitySet.ElementType)#>> and add virtual in front of it. Now you can check out the generated xxx.Context.cs file to be sure it’s not doing crazy things.

While you’re at it, since you’re modifying the code templates, follow these awesome instructions to xml-document your generated entities.

Now, following the MSDN article, in your query tests (the ones returning a set of data), you will have to manually create the data to return, and “bind” it to the mock instance. Since you will have to do that in each of your query tests, don’t forget to extract it to a method:

Faking objects with FakeItEasy

Remember that time (yesterday) when I created my own fake implementations for my tests? Man, was I crazy.

There is an awesome library called FakeItEasy, which ease up your fake implementations.

Now, instead of implementing your own IEntitiesContainer (or whatever your data layer injection interface is), you can tell FakeItEasy to generate a new fake of this interface, and you get a bunch of assertion methods on it thrown in for good measure.

It also helps you make sure you’re testing the right things. For instance, I had a test method return a list of paginated result, and went to great lengths to make sure the proper number of items were returned. After spending a bit of time trying to refactor my test (because FakeItEasy doesn’t make it easy to provide specific parameters), I found out I don’t care about the number of returned results, since this is tested elsewhere.