c# - 值不能为空。参数名称 : request

标签 c# unit-testing nunit httprequest httpresponsemessage

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

我在下面有这个 protected HttpResponseMessage 代码,当它返回时我的 Controller 正在调用它。

但是,报错:

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

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

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

错误显示在这一行:

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

这是我的 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)
        });
    }

最佳答案

你得到的原因:

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.

是因为Request对象是null

enter image description here

解决方案是在测试中创建一个 Controller 实例,例如:

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

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

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

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

关于c# - 值不能为空。参数名称 : request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38909810/

相关文章:

c# - 什么是好的、免费的 C# 单元测试覆盖工具?

nunit - 执行 specflow 功能的顺序

c# - RenderPartial,模型作为参数

c# - 将字符串写入 UTF-8 文件(无 BOM)时的奇怪行为 - 返回 ANSI 文件

xcode - 在 xcode 单元测试中加载文件

c# - 应该和 Json.NET : This passes? ! JToken.Parse ("{}").ShouldBe ("hello");

c# - C# 中 Math.Sin() 和 Math.Cos() 的精度

c# - 附加属性的统一

python - Doctest python 中的私有(private)方法

node.js - 如何测试 node.js websocket 服务器?