值不能为空。参数名称:请求

时间:2016-08-12 04:15:20

标签: c# unit-testing nunit httprequest httpresponsemessage

我使用nunit创建单元测试,所有这些代码在运行时都能正常运行。

我在下面有这个受保护的HttpResponseMessage代码,当它返回时我的控制器会调用它。

然而,错误:

  

"值不能为空。参数名称:request"正在显示。

当我检查请求时,实际上是null

问题: 我如何编码单元测试以返回HttpResponseMessage

此行显示错误:

  protected HttpResponseMessage Created<T>(T result) => Request.CreateResponse(HttpStatusCode.Created, Envelope.Ok(result));

这是我的控制器:

    [Route("employees")]
    [HttpPost]
    public HttpResponseMessage CreateEmployee([FromBody] CreateEmployeeModel model)
    {
        //**Some code here**//

        return Created(new EmployeeModel
        {
            EmployeeId = employee.Id,
            CustomerId = employee.CustomerId,
            UserId = employee.UserId,
            FirstName = employee.User.FirstName,
            LastName = employee.User.LastName,
            Email = employee.User.Email,

            MobileNumber = employee.MobileNumber,
            IsPrimaryContact = employee.IsPrimaryContact,
            OnlineRoleId = RoleManager.GetOnlineRole(employee.CustomerId, employee.UserId).Id,
            HasMultipleCompanies = EmployeeManager.HasMultipleCompanies(employee.UserId)
        });
    }

3 个答案:

答案 0 :(得分:12)

你得到的原因:

  

System.Web.Http.dll中发生了'System.ArgumentNullException'类型的异常,但未在用户代码中处理   附加信息:值不能为空。

是因为Request对象是null

enter image description here

解决方案是在测试中创建控制器的实例,例如:

    var myApiController = new MyApiController
    {
        Request = new System.Net.Http.HttpRequestMessage(),
        Configuration = new HttpConfiguration()
    };

这样,在创建MyApiController类的新实例时,我们正在初始化Request对象。此外,还需要提供相关的配置对象。

最后,您的Api控制器的单元测试示例可能是:

[TestClass]
public class MyApiControllerTests
{
    [TestMethod]
    public void CreateEmployee_Returns_HttpStatusCode_Created()
    {
        // Arrange
        var controller = new MyApiController
        {
            Request = new System.Net.Http.HttpRequestMessage(),
            Configuration = new HttpConfiguration()
        };

        var employee = new CreateEmployeeModel
        {
            Id = 1
        };

        // Act
        var response = controller.CreateEmployee(employee);

        // Assert
        Assert.AreEqual(response.StatusCode, HttpStatusCode.Created);
    }
}

答案 1 :(得分:3)

我认为当您新建Controller时,您没有实例化或分配您的Request属性(HttpRequestMessage)。我认为在通过单元测试调用Api方法之前必须指定请求。

您可能还需要配置(HttpConfiguration):

sut = new YourController()
    {
        Request = new HttpRequestMessage {
            RequestUri = new Uri("http://www.unittests.com") },

        Configuration = new HttpConfiguration()
    };

如果有效,请告诉我。

答案 2 :(得分:0)

此外,如果您的控制器有注射剂,您可以执行以下操作:

var controller= new MyController(injectionA, injectionB, injectionC)
{
    Request = new HttpRequestMessage(),
    Configuration = new HttpConfiguration()
};

我现在在易于理解的official doc上找到了它们。