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

Event-driven .NET: How to consume an SSE endpoint with HttpClient

Server-Sent Events (SSE) allow a client to subscribe to messages from the server. It creates a one-way stream from the server to the client. When the server has new messages for the client, it writes them to the stream. This is an alternative to the client polling the server for updates. Use the following to … Read more

C# – How to unit test async methods

Let’s say you have the following async method you want to test: Here’s how to unit test this: This is awaiting the method you’re testing. To await it, you must make the unit test method return async Task. This example is a bit simplistic. In the real world when you are working with async methods, … Read more