ASP.NET Core – How to unit test your middleware class

There are three requirements for unit testing a middleware class: Mock out RequestDelegate by defining a lambda that returns a Task (Task.FromException, Task.FromResult, or Task.FromCanceled). Mock out HttpContext by using DefaultHttpContext. The middleware function needs to be awaited, so your unit test needs to be defined with async Task. Here’s an example: This is a … Read more