Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

I want to use Unit Test only for this. Please help me out on this.

like image 583
Yasser Shaikh Avatar asked Oct 08 '12 10:10

Yasser Shaikh


People also ask

Is it possible to unit test Web API?

We have an option to create a Unit test project when we create a Web API project. When we create a unit test project with a web API project, Visual Studio IDE automatically adds Web API project reference to the unit test project.


1 Answers

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);     } } 
like image 56
tugberk Avatar answered Oct 15 '22 01:10

tugberk