简体   繁体   English

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

[英]Value cannot be null. Parameter name: request

I'm creating a unit test using nunit and all of this code works fine in runtime. 我正在使用nunit创建一个单元测试,所有这些代码在运行时都能正常工作。

I have this protected HttpResponseMessage code below that is being called by my controller when it returns. 我有下面这个受保护的HttpResponseMessage代码,当它返回时我的控制器会调用它。

However, an error: 但是,错误:

"Value cannot be null. Parameter name: request" is displaying. “值不能为空。参数名称:请求”正在显示。

And when I check the request, it is actually null . 当我检查请求时,它实际上是null

Question: How will I code my unit test to return the HttpResponseMessage ? 问题:如何编写单元测试以返回HttpResponseMessage

Error is shown in this line: 错误显示在此行中:

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

Here is my Controller: 这是我的控制器:

    [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)
        });
    }

The reason why you are getting: 你得到的原因:

An exception of type 'System.ArgumentNullException' occurred in System.Web.Http.dll but was not handled in user code Additional information: Value cannot be null. System.Web.Http.dll中发生类型为“System.ArgumentNullException”的异常但未在用户代码中处理附加信息:值不能为null。

is because the Request object is null . 是因为Request对象为null

在此输入图像描述

The solution for that is to create an instance of your controller in your tests such as: 解决方案是在测试中创建控制器的实例,例如:

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

In this way, when creating a new instance of the MyApiController class we are initializing the Request object. 这样,在创建MyApiController类的新实例时,我们正在初始化Request对象。 Moreover, it is also necessary to provide the associated configuration object. 而且,还必须提供相关的配置对象。

Finally, an example of Unit Test for your Api Controller could be: 最后,您的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);
    }
}

I think what happens is that you are not instantiating or assigning your Request property ( HttpRequestMessage ) when you new up your Controller. 我认为当您新建Controller时,您没有实例化或分配您的Request属性( HttpRequestMessage )。 I believe it's mandatory to specify the request prior calling into the Api method via your unit test. 我认为必须在通过单元测试调用Api方法之前指定请求。

You may also require a Configuration ( HttpConfiguration ): 您可能还需要配置( HttpConfiguration ):

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

        Configuration = new HttpConfiguration()
    };

Let me know if that works. 如果有效,请告诉我。

Also, if your controller has injections, you can do: 此外,如果您的控制器有注射,您可以:

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

I find them all on the easy to understand official doc now. 我现在发现它们都是易于理解的官方文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM