Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC4 TDD - System.ArgumentNullException: Value cannot be null.

I'm new to mvc4 and also TDD.

When I try running this test it fails, and I have no idea why. I have tried so many things I'm starting to run around in circles.

    // GET api/User/5
    [HttpGet]
    public HttpResponseMessage GetUserById (int id)
    {
        var user = db.Users.Find(id);
        if (user == null)
        {
            //return Request.CreateResponse(HttpStatusCode.NotFound);
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        }
        return Request.CreateResponse(HttpStatusCode.OK, user);

    }


    [TestMethod]
    public void GetUserById()
    {
        //Arrange
        UserController ctrl = new UserController();
        //Act

        var result = ctrl.GetUserById(1337);

        //Assert
        Assert.IsNotNull(result);
        Assert.AreEqual(HttpStatusCode.NotFound,result.StatusCode);

    }

And the results:

Test method Project.Tests.Controllers.UserControllerTest.GetUserById threw exception: 
System.ArgumentNullException: Value cannot be null. Parameter name: request
like image 738
ArniReynir Avatar asked Feb 25 '13 15:02

ArniReynir


1 Answers

You test is failing because the Request property that you are using inside your ApiController is not initialized. Make sure you initialize it if you intend to use it:

//Arrange
var config = new HttpConfiguration();
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/user/1337");
var route = config.Routes.MapHttpRoute("Default", "api/{controller}/{id}");
var controller = new UserController
{
    Request = request,
};
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;

//Act
var result = controller.GetUserById(1337);
like image 136
Darin Dimitrov Avatar answered Oct 24 '22 05:10

Darin Dimitrov