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.

πŸ‘‹ While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay