Writing Unit Test for methods that use User.Identity.Name in ASP.NET Web API

Yasser Shaikh picture Yasser Shaikh · Oct 8, 2012 · Viewed 24.2k times · Source

I am writing test cases using the Unit Test for ASP.NET Web API.

Now I have an action which makes a call to some method I have defined in the service layer, where I have used the following line of code.

string username = User.Identity.Name;
// do something with username
// return something

Now how to I create unit test method for this, I am getting null reference exceptions. I am kinda new to writing unit test and stuff.

And I want to use Unit Test only for this.

Please help me out on this. Thanks.

Answer

tugberk picture tugberk · Oct 8, 2012

The below one is only one way of doing this:

public class FooController : ApiController {

    public string Get() {

        return User.Identity.Name;
    }
}

public class FooTest {

    [Fact]
    public void Foo() {

        var identity = new GenericIdentity("tugberk");
        Thread.CurrentPrincipal = new GenericPrincipal(identity, null);
        var controller = new FooController();

        Assert.Equal(controller.Get(), identity.Name);
    }
}