How fake System.Security.Principal.IIdentity using FakeItEasy?

721 Views Asked by At

In my app users loging in via WIF. User's credentials is stored in System.Security.Principal.IIdentity. Now i want to test CreateUser() method. I have to in some way fake that object. I try to do something like this: -extract method which returns that object:

public IIdentity GetIdentity()
{
    return Thread.CurrentPrincipal.Identity;
}

and then in test file do something like this:

    var identity = new GenericIdentity("[email protected]");
    A.CallTo(() => _userRepository.GetIdentity()).Returns(identity);

But it doesn't work. Any ideas how to do that in the best way?

2

There are 2 best solutions below

0
On BEST ANSWER

Have a look at WIF's ClaimsPrincipalHttpModule. It will transform a Windows identity into an IClaimsPrincipal without needing an STS.

Also have a look at SelfSTS which is an extremely useful tool.

0
On

Create a fake WindowsIdentity class:

public class FakeWindowsIdentity : WindowsIdentity
{
    private readonly string _name;

    public FakeWindowsIdentity(string sUserPrincipalName) 
        : base(GetAnonymous())
    {
        _name = sUserPrincipalName;
    }

    public override string Name => _name;
}

I'm using FakeItEasy, so I create a fake IPrincipal like so:

IPrincipal fakeUser = A.Fake<IPrincipal>();
A.CallTo(() => fakeUser.Identity)
    .Returns(new FakeWindowsIdentity("domain\\username"));

To assign to Thread:

Thread.CurrentPrincipal = fakeUser;