Should you unit-test API/MVC controllers in ASP.NET Core?

Should you unit-test API/MVC controllers in ASP.NET Core?

In this post I discuss unit testing of API/MVC controllers in ASP.NET Core and some of the difficulties you face.

Based on Betteridge's law of headlines: no!

But based on recent twitter activity, that's no doubt a somewhat controversial opinion, so in this post I look at what a unit-test for an API controller might look like, what a unit-test is trying to achieve, and why I think integration tests in ASP.NET Core give you far more bang-for-your-buck.

I start by presenting my thesis, about why I don't find unit tests of controllers very useful, acknowledging the various ways controllers are used in ASP.NET Core. I'll then present a very simple (but representative) example of an API controller, and discuss the unit tests you might write for that class, the complexities of doing so, as well as the things you lose by testing the controller outside the ASP.NET Core MVC framework as a whole.

This post is not trying to suggest that unit tests are bad in general, or that you should always use integration tests. I'm only talking about API/MVC controllers here.

Where does the logic go for an API/MVC controller?

The MVC/API controllers people write generally fall somewhere on a spectrum:

  • Thick controllers—The action method contains all the logic for implementing the behaviour. The MVC controller likely has additional services injected in the constructor, and the controller takes care of everything. This is the sort of code you often see in code examples online. You know the sort—where an EF Core DbContext, or IService is injected and manipulated in the action method body:
public class BlogPostController : Controller
{
    // Often this would actually be an EF Core DB Context injected in constructor!
    private readonly IRepository _repository;
    public BlogPostController(IRepository repository) => _repository = repository;

    [HttpPost]
    public ActionResult<Post> Create(InputModel input)
    {
        if(!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        // Some "business logic" 
        if(_repository.IsSlugAvailable(input.Slug)
        {
            ModelState.AddError("Slug", "Slug is already in use");
            return BadRequest(ModelState);
        }

        var model = new BlogPost
        {
            Id = model.Id,
            Name = model.Name,
            Body = model.Body,
            Slug = model.Slug
        });
        _repository.Add(model);

        return result;
    }
}
  • Thin controllers—The action method delegates all the work to a separate service. In this case, most of the work is done in a separate handler, often used in conjunction with a library like Mediatr. The action method becomes a simple mapper between HTTP-based models/requests/responses, and domain-based models/commands/querys/results. Steve Smith's API endpoints project is a good example that is pushing this approach.
public class BlogPostController : BaseApiController
{
    [HttpPost]
    public async Task<IActionResult> Create([FromBody]NewPostCommand command)
    {
        var result = await Mediator.Send(command);
        return Ok(result);
    }
}

So which approach do I use? Well, as always it depends. In general, I think the second option is clearly the more scalable, manageable, and testable option, especially when used in conjunction with conventions or libraries that enforce that practice.

But sometimes, I write the other types of controllers. Sometimes it's because I'm being sloppy. Sometimes it's because I need to do some HTTP related manipulation which wouldn't make sense to do in a command handler. Sometimes the action is so simple it just doesn't warrant the extra level of indirection.

What I don't do (any more 🤦‍♂️), is put important domain logic in action methods. Why? Because it makes it harder to test.

"But you can unit-test controllers!" I hear you cry. Well…yes…but…

What don't you test in controller unit tests

MVC/API controllers are classes, and actions are just methods, so you can create and invoke them in unit tests the same way you would any other system under test (SUT).

The trouble is, in practice, controllers do most of their useful work as part of a framework, not in isolation. In unit tests, you (intentionally) don't get any of that.

In this section I highlight some of the aspects of MVC controllers that you can't easily test or wouldn't want to test in a unit test.

asp.net core testing mvc

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

jQuery Ajax CRUD in ASP.NET Core MVC with Modal Popup

In this article, we’ll discuss how to use jQuery Ajax for ASP.NET Core MVC CRUD Operations using Bootstrap Modal. With jQuery Ajax, we can make HTTP request to controller action methods without reloading the entire page, like a single page application.

MVC User Registration & Login with ASP.NET Core Identity

In this article, we will discuss the quickest way to use ASP.NET Core Identity for User Login and Registration in a new or existing MVC application.

Asp.Net Core MVC Bangla Tutorial -01 (Beginners To Expert Level)

LIKE | COMMENT | SHARE | SUBSCRIBE What is ASP.NET Core?????? ASP.NET Core is an open source and cloud-optimized web framework for developing modern web appl...

Asp.Net Core MVC Bangla Tutorial - 04 (Beginners To Expert Level)

ASP.NET Core is an open-source, cross-platform framework for building modern, cloud-based web apps on Windows, macOS, or Linux. ASP.NET Core provides the fol...

Asp.Net Core MVC Bangla Tutorial - 05 (Beginners To Expert Level)

ASP.NET Core is an open-source, cross-platform framework for building modern, cloud-based web apps on Windows, macOS, or Linux. ASP.NET Core provides the fol...