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.
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.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With