DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

4 3

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay