0

I'm new to ASP.NET Core. I need to mock ClaimsPrincipal in an unit test in C#, for the following method:

public class MyTestHelper
{
    public static string getName(this ClaimsPrincipal principal)
    {
        string name = principal.Claims.Any(c => c.Type= "test") ? 
                           Convert.ToString(principal.Claims.Where(i => i.Type = "test").FirstOrDefault().Value);
    }
}

This is what I've tried so far. But I get an error message saying cannot convert from IPrincipal to ClaimsPrincipal:

[Test]
public void getNameTest()
{
    var principal  =  new Mock<IPrincipal>;
    string name =  MyTestHelper.getName(principal.Object);
}

Thank you for your help!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mitu
  • 13
  • 3
  • Does this answer your question? [Mocking IPrincipal in ASP.NET Core](https://stackoverflow.com/questions/38557942/mocking-iprincipal-in-asp-net-core) – Felix Mar 24 '23 at 20:42

1 Answers1

0

The reason your exception is being thrown is that your method is expecting the specific ClaimsPrincipal implementation of IPrincipal, but your mock is only creating a mock of IPrincipal (not ClaimsPrincipal itself).

Honestly, there is no need to mock ClaimsPrincipal though. It is a lightweight public class with a public constructor, which means you can create one for your test very easily (easier than mocking and setting up claims to be returned). We use something like this in our unit tests, where you would pass in the claims you want:

public static ClaimsPrincipal CreateClaimsPrincipal(params Claim[] identityClaims)
{
    var identity = new ClaimsIdentity(identityClaims);

    var principal = new ClaimsPrincipal(identity);

    return principal;
}

If for some reason you still really want to mock ClaimsPrincipal, you could do it like this:

var identityClaims = new Claim[] { /* add claims here */ };

var identity = new Mock<ClaimsIdentity>();
identity.Setup(x => x.Claims).Returns(identityClaims);

var claimsPrincipal = new Mock<ClaimsPrincipal>();
claimsPrincipal.Setup(x => x.Identity).Returns(identity.Object);
digital_jedi
  • 346
  • 2
  • 7