ASP.NET Core 2.1 middlewares part 2: Unit test a custom middleware

 

How to unit test a middleware ?

It’s very easy to unit test a middleware in ASP.NET Core.

There three important things to understand here.

First the Invoke method takes in parameter an HttpContext instance.

We all know how it’s painful to mock an HttpContext… We don’t need! ASP.NET Core provide a “fake” HttpContext named DefaultHttpContext. Feeling better now ? 🙂

Second thing to know, if you need to unit test the Response body property you have to initialize it tourslef like this:

var context = new DefaultHttpContext();
context.Response.Body = new MemoryStream();

and just before reading the content, reset the body’s stream position back to 0.

context.Response.Body.Seek(0, SeekOrigin.Begin);

And finally, the RequestDelegate object passed in parameter of the middleware’s constructor is simply a delegate, Action exactly.

We are ready to unit test our custom middleware

In these scenarii, we will use XUnit and FluentAssertion

Case 1: scenario with a custom error:

public class CustomExceptionMiddlewareTests
{
   [Fact]
   public async Task WhenACustomExceptionIsRaised_CustomExceptionMiddlewareShouldHandleItToCustomErrorResponseAndCorrectHttpStatus()
   {
      // Arrange
      var middleware = new CustomExceptionMiddleware((innerHttpContext) =>
      {
         throw new NotFoundCustomException("Test", "Test");
      });

      var context = new DefaultHttpContext();
      context.Response.Body = new MemoryStream();

      //Act
      await middleware.Invoke(context);

      context.Response.Body.Seek(0, SeekOrigin.Begin);
      var reader = new StreamReader(context.Response.Body);
      var streamText = reader.ReadToEnd();
      var objResponse = JsonConvert.DeserializeObject<CustomErrorResponse>(streamText);

      //Assert
      objResponse
      .Should()
      .BeEquivalentTo(new CustomErrorResponse { Message = "Test", Description = "Test" });

      context.Response.StatusCode
      .Should()
      .Be((int)HttpStatusCode.NotFound);
   }
}

Case 2: scenario with an unhandled error:

public class CustomExceptionMiddlewareTests
{
   [Fact]
   public async Task WhenAnUnExpectedExceptionIsRaised_CustomExceptionMiddlewareShouldHandleItToCustomErrorResponseAndInternalServerErrorHttpStatus()
   {
      // Arrange
      var middleware = new CustomExceptionMiddleware(next: (innerHttpContext) =>
      {
         throw new Exception("Test");
      });

      var context = new DefaultHttpContext();
      context.Response.Body = new MemoryStream();

      //Act
      await middleware.Invoke(context);

      context.Response.Body.Seek(0, SeekOrigin.Begin);
      var reader = new StreamReader(context.Response.Body);
      var streamText = reader.ReadToEnd();
      var objResponse = JsonConvert.DeserializeObject<CustomErrorResponse>(streamText);

     //Assert
     objResponse
     .Should()
     .BeEquivalentTo(new CustomErrorResponse { Message = "Unexpected error", Description = "Unexpected error" });

     context.Response.StatusCode
     .Should()
     .Be((int)HttpStatusCode.InternalServerError);
   }
}

 

Easy isn’t it ? 😉

How to fix unit test discovery in VS 2017 with MSTest V2?

Introduction

Microsoft Test Framework “MSTest V2” is the evolution of the Microsoft Test Framework and Adapter.

I wanted to try this new framework test by creating a new test project from an empty class library instead of using a MsTest test project and I got in trouble…..

My unit tests were not discovered by Visual Studio 2017.

How did I fix this?

What I have installed

I have installed the following packages:

Then I checked if my unit tests were displayed on Test Explorer and they were not 🙁 , I even tried to run them but I got this message:

What I did to find the issue

There are many reason that can explain this issue, so to know what’s going on I ran the following command line in the unit test project directory:

> dotnet test

It’s the same command that Visual Studio executes but by this way, you will see the precise error if there is an error during execution of the command line:

In my case I knew easily what I missed since the beginning!

I missed the installation of Microsoft.NET.Tests.Sdk package!

I just installed it and I was able to run my tests 🙂

Hope it has helped you 🙂

How to unit test private methods in .NET Core applications? (even if it’s bad)

Introduction

Yes it’s bad and dirty!

Since your private methods are only an implementation detail whose existence and behavior is only justified by their use in public methods, then these private methods are automatically tested through public method tests.

In other words, once your public methods are tested, your private methods should be fully covered. If this is not the case, it is either that you have forgotten tests or that your private method does things that are of no use to meet the needs of your public methods. In this case, it is probably necessary to clean them.

“Yes, but my private methods are big and complicated, tests would be very practical Sometimes, we see private methods that are full of stuff or things so complicated, that having tests would still be very practical.”

That is true. We see some.

Even myself I have been I was confronted with this kind of problem:

“Sometimes a bug is located in a private method and I do not want to recreate all the context necessary to call the public method.”

That’s why I’m going to show you how to test them, but do not forget that this should be truly exceptional.

How to?

This is really more simple than you think! we will just use Reflection.

In this example, I will use XUnit and FluentAssertion.

Let’s define a class with a private method:

namespace XUnitAndFluentAssertionDemo
{
   public class Hello
   {
      private string _firstName { get; set; }
      private string _lastName { get; set; }

      public Hello(string firstName, string lastName)
      {
         _firstName = firstName;
         _lastName = lastName;
      }

      public string HelloMan()
      {
        if (string.IsNullOrEmpty(_firstName))
        throw new MissingFirstNameException();

        return this.HelloMan(_firstName, _lastName);
      }

      private string HelloMan(string firstName, string lastName)
      {
         return $"Hello {firstName} {lastName} !";
      }

   }

   public class MissingFirstNameException: Exception
   {
      public MissingFirstNameException(): base("FirstName is missing")
      {
      }
   }
}

Now let’s write the unit test using Reflection:

We will use the well known function Activator.CreateInstance and fetch its methods and properties using Linq, then invoke the method to test with the well known method Invoke:

namespace UnitTests
{
   public class HelloTests
   {
      [Fact]
       public void PrivateHelloManShouldBeWellFormated()
       {
          // Arrange
          var firstName = "John";
          var lastName = "Doe";

          Type type = typeof(Hello);
          var hello = Activator.CreateInstance(type, firstName, lastName);
          MethodInfo method = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
          .Where(x => x.Name == "HelloMan" && x.IsPrivate)
          .First();

          //Act
          var helloMan = (string)method.Invoke(hello, new object [] {firstName, lastName});

         //Assert
         helloMan
         .Should()
         .StartWith("Hello")
         .And
         .EndWith("!")
         .And
         .Contain("John")
         .And
         .Contain("Doe");
       }
    }
}

Conclusion

Wondering “how to test a private method” should raise an alarm.

You should first find a solution to avoid this, review your code, but often it’s not easy because you maintain very old legacy code or your colleagues are stubborn :).

Anyway, I hope this article would help you.

Good luck 🙂