Reputation: 377
In the Configure method I'm calling my extension method
app.UseJsonResponse();
My extension method
public static class JsonResponseExtension
{
public static IApplicationBuilder UseJsonResponse(this IApplicationBuilder app)
{
app.UseMiddleware<JsonResponseMiddleware>();
return app;
}
}
I want to test UseJsonResponse method. I wrote
public class JsonResponseExtensionTest
{
[Fact]
public void UseJsonResponse()
{
var iApplicationBuilderMock = new Mock<IApplicationBuilder>();
iApplicationBuilderMock
.Verify(b => b.UseMiddleware<JsonResponseMiddleware>(), Times.Never);
}
}
And i'm getting an exception
Extension methods (here: UseMiddlewareExtensions.UseMiddleware) may not be used in setup / verification expressions.
How to resolve this problem?
Upvotes: 3
Views: 1556
Reputation: 3213
UseMiddleware
is an extension which can't be mocked, you've got to mock what the extension invokes on the interface. In this case the method is probably
IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware);
I would need to know more about JsonResponseMiddleware
as the UseMiddleware
extension, and the extensions that it too invokes, has quite a bit going on, some of it to do with the interfaces JsonResponseMiddleware
implements. For reference, the UseMiddleware
extensions can be found here.
With the information at hand, after invoking your UseJsonResponse
extension the following will verify that Use
was invoked once.
[Test]
public void Test1()
{
var applicationBuilderMock = new Mock<IApplicationBuilder>();
var mockedApplicationBuilder = applicationBuilderMock.Object;
mockedApplicationBuilder.UseJsonResponse();
applicationBuilderMock.Verify(x => x.Use(It.IsAny<Func<RequestDelegate, RequestDelegate>>()), Times.Once);
}
To take it further I would need to know more about JsonResponseMiddleware
as mentioned. It also looks like a lot more effort to include a check for the JsonResponseMiddleware
type.
Upvotes: 3