I am trying to confirm via a unit test that middleware is actually being added to the pipeline. I have the following static method that adds the middleware. This is what I am testing.
public static class HandleDbUpdateExceptionExtensions
{
public static IApplicationBuilder UseDbUpdateExceptionHandler(this IApplicationBuilder builder)
{
return builder.UseMiddleware<DbUpdateExceptionHandler>();
}
}
I know it's actually working because the middleware runs on my site. However, I'd like to write a unit test to ensure it's always included in future builds. My unit test, however, fails:
[Fact(DisplayName = "Exception handler is added to IApplicationBuilder")]
public void DbUpdateExceptionHandler_Added_To_IApplicationBuilder()
{
var builder = new Mock<IApplicationBuilder>().Object;
builder.UseDbUpdateExceptionHandler();
Assert.NotNull(builder.ApplicationServices);
//var test = builder.ApplicationServices.GetService(typeof(DbUpdateExceptionHandler));
}
builder.ApplicationServices
is null so the test currently fails. I assume that it is failing because I am just mocking IApplicationBuilder
but there is very little relevant material online about unit testing the existance of .Net Core middleware.
Any help is greatly appreciated!
IApplicationBuilder
orIServiceProvider
method that gives you the pipeline or confirms whether or not a specific class (or even interface) is in the pipeline. – Wigging