Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .Net Core 2 and Moq, how do you setup a HTTP Context to fake authentication?

I am using Moq to make automated tests in my .net core 2 app. We use bearer authentication and need to be able to pull out the name from the HttpContext object to make sure we have the right user:

var userName = HttpContext.User.Identity.Name;

I have found tons of examples using System.Web but none that let me mockup a Core 2 setup.

like image 505
David Avatar asked Dec 17 '25 11:12

David


2 Answers

You can achieve the same thing without having to mock anything and use the already existing classes provided by the framework.

public class ContextHelper {
    public static HttpContext GetHttpContext(string name = "[email protected]") {
        var identity = new GenericIdentity(name, "test");
        var contextUser = new ClaimsPrincipal(identity);
        var httpContext = new DefaultHttpContext() {
            User = contextUser
        };
        return httpContext;
    }
}

just because we have the ability to mock certain things does not mean that we have to mock most of the times.

like image 54
Nkosi Avatar answered Dec 19 '25 05:12

Nkosi


Ok, so after cobbling together help from a few older links (i.e. Setting HttpContext.Current.Session in a unit test) I was able to get this working, thought I would post it here for posterity:

public class ContextHelper
{
    public static HttpContext GetMockedHttpContext()
    {
        var context = new Mock<HttpContext>();
        var identity = new Mock<IIdentity>();
        var contextUser = new Mock<ClaimsPrincipal>();
        contextUser.Setup(ctx => ctx.Identity).Returns(identity.Object);
        identity.Setup(id => id.IsAuthenticated).Returns(true);
        identity.Setup(id => id.Name).Returns("[email protected]");
        context.Setup(x => x.User).Returns(contextUser.Object);

        return context.Object;
    }
}

This allows my unit tests to pull out the user name of my fake user easily.

I call it like this:

var uc = new UserController();
uc.ControllerContext.HttpContext = ContextHelper.GetMockedHttpContext();
uc.WhateverMethodGoesHere();
like image 24
David Avatar answered Dec 19 '25 05:12

David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!