我正在使用 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
。
解决方案是在测试中创建一个 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/