DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

C#: How to mock HttpContext methods such as ForbidAsync?

When writing unit test, we need to mock "HttpContext" methods such as ForbidAsync, SignInAsync, etc.

As these methods are extension method, we need to know which actual method to mock.

Unit Test

This is the code I use to test "ForbidAsync".

Mock<IAuthenticationService> mockedIAuthenticationService = new();
mockedIAuthenticationService
    .Setup(x => x.ForbidAsync(It.IsAny<HttpContext>(), It.IsAny<string>(), It.IsAny<AuthenticationProperties>()))
    .Returns(Task.FromResult((object)true));
Mock<IServiceProvider> mockedIServiceProvider = new();
mockedIServiceProvider
    .Setup(x => x.GetService(typeof(IAuthenticationService)))
    .Returns(mockedIAuthenticationService.Object);
Mock<HttpContext> mockedHttpContext = new Mock<HttpContext>();
mockedHttpContext.Setup(x => x.RequestServices).Returns(mockedIServiceProvider.Object);
Enter fullscreen mode Exit fullscreen mode

Where does it come from?

AuthenticationHttpContextExtensions indicates it comes from IAuthenticationService, which is obtained via context.RequestServices.GetService<IAuthenticationService>().

So I just need to mock IServiceProvider and IServiceProvider.

Hope this helps me again in the future.

Top comments (2)

Collapse
 
pbouillon profile image
Pierre Bouillon

Hey, thanks for sharing!

I think your last part may benefit from a small example showcasing how you achieve your test it in practice 😄

Collapse
 
kenakamu profile image
Kenichiro Nakamura

I need to dig into source code these days to figure out these things as we don't have enough document or our scenario could be a bit unique? Anyway I thought it might be good to share how I found it :D