DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 968,873 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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.

Latest 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 Author

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

๐ŸŒš Life is too short to browse without dark mode