1

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("mymail@mydomain.com");
    A.CallTo(() => _userRepository.GetIdentity()).Returns(identity);

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

Kamil Będkowski
  • 1,092
  • 4
  • 16
  • 36

2 Answers2

1

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.

rbrayb
  • 46,440
  • 34
  • 114
  • 174
0

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;
codeMonkey
  • 4,134
  • 2
  • 31
  • 50