MVC4 TDD-系统.ArgumentNullException:值不能为null
本文关键字:不能 null TDD- 系统 ArgumentNullException MVC4 | 更新日期: 2023-09-27 18:00:54
我是mvc4和TDD的新手。
当我尝试运行这个测试时,它失败了,我不知道为什么。我已经尝试了很多东西,我开始绕圈子跑了。
// 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);
}
结果:
Test method Project.Tests.Controllers.UserControllerTest.GetUserById threw exception:
System.ArgumentNullException: Value cannot be null. Parameter name: request
您的测试失败,因为您在ApiController中使用的Request
属性未初始化。如果你打算使用它,请确保你初始化了它:
//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);