ASP.NET Core – adding controllers directly from integration tests

1. Introduction

From time to time it might happen, that you need to test certain parts of your ASP.NET Core configuration without hitting publicly visible business-related controllers. For instance, in my case, I wanted to make sure that my ASP.NET Core API behavior is consistent with the original API written in Nancy. As you might expect there are quite a lot of differences between both of the frameworks, so let’s focus on testing one thing, namely non-nullable reference type handling. Long story short, in order to have the same behavior in ASP.NET Core as in Nancy I had to add the following line of configuration

This one prevents ASP.NET Core from marking non-nullable reference type properties in request as required. Having that configuration ready, I wanted to test it with an end to end test. Because there was no business-related logic yet, I needed to figure out the way of adding API controllers to my application directly from the integration tests. Here is how you can achieve that.

2. Accessing ApplicationPartManager from integration tests

ASP.NET Core is able to compose your API from different parts thanks to ApplicationPartManager. By default, you don’t use it directly but rather with IMvcBuilder AddApplicationPart extension method while setting up your application

However, there is no easy way of getting IMvcBuidler from the integration tests(at least I didn’t find a proper way of doing that without tampering too much with the original application pipeline) so we need to access ApplicationPartManager directly. Inspecting the source code of the framework you will find that ApplicationPartManager can be retrieved directly from IServiceCollection with following code

Applying similar code to the WebApplicationFactory will allow us to add controllers directly from tests

3. Handling private controllers

The solution presented below works nice, however it has couple of drawbacks. First of all, it only discovers public non-nested controllers. Second of all, it will always add all controllers from given assembly – which potentially might affect other integration tests. In order to get rid of these drawbacks, we need to tell ApplicationPartManager to include only selected controllers. We can achieve that by adding additional IApplicationFeatureProvider<ControllerFeature> to the list of FeatureProviders.

Putting it all together and applying some refactoring we will end up with following code

Source code for this post can be found here

ASP.NET Core – adding controllers directly from integration tests

Mocking downstream services with Mountebank

1. Introduction

I’m a part of a team which creates large enterprise platform for the banking sector. Due to the fact that we operate in the financial area, our application consumes a high amount of downstream services. One of the major problems we are facing at the moment is the inaccessibility of those services on DEV and UAT environments. It often happens that one of those services is down for quite some time, so our development speed is impaired. The bigger problem, however, is the fact that our end-to-end tests are red. Having a red test on TeamCity for a long time is a really annoying thing because basically at this point, we just automatically assume that all of the failures are caused by issues with downstream systems. Fortunately, we finally decided to get rid of this problem and this is the solution we came up with.

2. Background

Before I go to the implementation details, take a look at a sample implementation of situation I described at the very beginning. Let’s assume that we have WCF service which contains business logic of our application and it is consumed by the UI side

BookingFacade uses Pricer service which basically is just a wrapper for external/downstream service we have to use in order to retrieve some data (and we do not have an ownership of that service).

Very simple end-to-end test for BookingFacade can look like that

As I mentioned before, everything is fine as long as all of the downstream systems are working. The moment one of them is down, our tests start failing.

3. Implementation

General idea to fix this problem is to use fake downstream systems during end-to-end testing. In order to do that we use combination of custom compilation profile, app.config transformations and mountebank test doubles.

3.1 Setting up transformations

First of all we will create a custom compilation profile called test.integration which will be used for running tests with mocked downstream systems (we want to preserve the normal use of downstreams for Debug and Release mode). In order to do that, go to ConfigurationManager
and follow the steps presented in the pictures below

Now it is time to prepare our app.config for transformations. We can do it manually but for sake of simplicity I will use SlowCheetah extension. Go to Tools->Extensions and Updates and install
SlowCheetah – XML Transforms. Once extension is installed you will see a Add Transform item in a config files’ context menu.
Clicking Add Transform will create three files: App.Debug.config, App.Release.config and App.Test.Integration.config. What is more, some additional changes will be added to your csproj file, which will be responsible for applying transformations during a build process. These three additional files hold information about config transformations. The default App.config file looks like that

Nothing special in here but note the empty file attribute in appSettings node. The value of this attribute will be replaced with proper filename during transformation process. In order to do that let’s implement tramsforms for every of three config files we use




As you can see I apply SetAttributes transform for appSettings node, which means that the transformation will replace appSettings node attributes from app.config file with appSettings node attributes from transform file. You can preview results of transformation by clicking Preview Transform context menu option available for every of our transform files
As you’ve probably already figured it out app.settings.debug and app.settings.release fileses contain real downstream endpoints and app.settings.tests.integration contains addresses of fake endpoints. Of course you have to create those files and copy them to output directory during the build (for instance by using Copy to Output directory option).

3.2. Creating fake downstreams with mountebank

Setting up fake downstream systems completely from scratch would be a very painful and time consuming process. Fortunately there are tools which can make this task easier. The tool I use is called mountebank – you can easily install it via npm

Having mountebank on board it is time to configure it, so that it acts as fake Pricer service. It can be done in couple of ways but I will go with file based configuration. You can run the tool using following command

Where impostors.ejs is a configuration file with following structure

<% include pricer.json %> is EJS syntax which (in this case) allows you to split configuration into multiple files. As you’ve probably already figured it out, Pricer.json contains the actual mock configuration for Pricer service. The initial mock object consists of couple of properties which setup the name, port and protocol for given mock.

Note that we do not specify the address of mock but just a port. Mountebank by default runs on http://localhost:2525 and mocks listen on http://localhost:{port}. The actual magic happens in stubs property.
Here is an example of stub/mock for GetTradingDates method.

As you can see stub object consists of two properties

  • responses
  • predicates

responses property is an array of objects mountebank will be using to create a response. If you insert multiple items into array, they will be utilized using round robin algorithm. Note that you don’t have to create a full response (with all the headers etc.) just use “is” property which will fill the default values for you. More about that topic can be found here but in most of the cases setting value for “body” property will be enough for you.

predicates property is an array of predicates which will be used during matching process. Predicate object can be quite complex, it supports lots of different matching techniques. In this case, for simple GET method I just use equals operator to match HTTP verb and HTTP method.
The same technique can be used for stubbing POST methods. However, in this case, you can also perform matching against the body of the request. The one thing you have to remember is that body property is not an object but string. So in my case, if I want to make a stub for GetPrice which takes as params following request object

I can write for instance this stub

Of course for more complex request it is pointless to write every possible combination of params. Fortunately you can create fallback/default stub which will match everything

If you put this at the very end of stubs array it will not interfere with other stubs.
This is of course just a tip of the iceberg when it comes to predicate matching. Explanation of all possible matching options can be found here

4. Results

From now on running tests against test.integration compilation profile and having mountebank working in the background, our tests will be green.
Source code for this post can be found here

Mocking downstream services with Mountebank