gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:58:19 25 4
gpt4 key购买 nike

我是 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);

关于c# - MVC4 TDD - System.ArgumentNullException : Value cannot be null.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15070315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com