简体   繁体   中英

Value cannot be null. Parameter name: request

I'm creating a unit test using nunit and all of this code works fine in runtime.

I have this protected HttpResponseMessage code below that is being called by my controller when it returns.

However, an error:

"Value cannot be null. Parameter name: request" is displaying.

And when I check the request, it is actually null .

Question: How will I code my unit test to return the 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.

is because the Request object is 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. Moreover, it is also necessary to provide the associated configuration object.

Finally, an example of Unit Test for your Api Controller could be:

[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. I believe it's mandatory to specify the request prior calling into the Api method via your unit test.

You may also require a Configuration ( 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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