【问题标题】:MVC4 TDD - System.ArgumentNullException: Value cannot be null.MVC4 TDD - System.ArgumentNullException:值不能为空。
【发布时间】:2013-02-10 19:03:34
【问题描述】:

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

【问题讨论】:

  • 在你的调试器中使用Step over并输入方法,必须是null
  • 附带说明,单元测试不应该访问像 db 这样的静态资源。您应该注入这些依赖项。当您的数据库更改时会发生什么?你的单元测试没用!
  • 我猜想 db 为空或 db.Users 为空。使用调试器检查
  • 当我通过 HTTP 请求调用我的 API 时,它会响应数据和 404(如果不可用)。感谢有关使用静态的提示,我会这样做。
  • 如果我测试静态数据,空错误可能会消失

标签: c# asp.net-mvc-4 tdd


【解决方案1】:

您的测试失败,因为您在 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);

【讨论】:

    猜你喜欢
    • 2021-08-01
    • 2020-03-01
    • 2020-09-25
    • 2019-11-01
    • 1970-01-01
    • 2018-07-10
    • 2021-10-11
    • 1970-01-01
    • 2021-08-29
    相关资源
    最近更新 更多