Salman Khan
Salman Khan

Reputation: 13

How to write unit test for HttpContext.Current.Request.Headers

Below is an Example.

public class MyController : Controller
{
    [Route("~/api/mycontroller")]
    [HttpGet]
    public int ID()
    {
        try
        {
            return somecontroller.getID(ID);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

Above it the controller that is fetching the ID from the below controller. Below is the controller that it is inherited.

public class Controller : ApiController
{
    public int ID
    {
        get
        {
            return int.Parse(HttpContext.Current.Request.Headers["ID"]);
        }
    }
}

How do i write unit test case for the following.???

Upvotes: 1

Views: 1146

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038880

Oh, unit testing HttpContext.Current. That's one of my favorites :-)

You can't write a unit test for something that depends on HttpContext.Current. So if you want to write testable code the first step is to search in your entire solution for the HttpContext.Current keyword and simply wipe them out from existence.

In this particular case you would of course replace them with the corresponding abstraction:

public class Controller : ApiController
{
    public int ID
    {
        get
        {
            return int.Parse(Request.Headers.GetValues("ID").FirstOrDefault());
        }
    }
}

Now it's completely trivial to unit test your Web API controller properly:

// arrange
var sut = new MyController();
sut.Request = new HttpRequestMessage();
sut.Request.Headers.TryAddWithoutValidation("ID", "5");


// act
var actual = sut.SomeControllerAction();

// assert
Assert.AreEqual(5, actual);

Upvotes: 1

Related Questions