加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – MVC4 TDD – System.ArgumentNullException:值不能为空.

发布时间:2020-12-15 03:56:58 所属栏目:百科 来源:网络整理
导读:我是新来的mvc4和TDD. 当我尝试运行此测试失败,我不知道为什么.我尝试了很多事情,我开始在圈子里跑来跑去. // GET api/User/5 [HttpGet] public HttpResponseMessage GetUserById (int id) { var user = db.Users.Find(id); if (user == null) { //return Re
我是新来的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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读