use*_*948 14 c# nunit unit-testing httprequest httpresponsemessage
我正在使用nunit创建一个单元测试,所有这些代码在运行时都能正常工作.
我有HttpResponseMessage
下面这个受保护的代码,当它返回时我的控制器会调用它.
但是,错误:
"值不能为空.参数名称:请求"正在显示.
当我检查请求时,实际上是null
.
问题:如何编码我的单元测试以返回HttpResponseMessage
?
错误显示在此行中:
protected HttpResponseMessage Created<T>(T result) => Request.CreateResponse(HttpStatusCode.Created, Envelope.Ok(result));
Run Code Online (Sandbox Code Playgroud)
这是我的控制器:
[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)
});
}
Run Code Online (Sandbox Code Playgroud)
Fel*_*ruz 18
你得到的原因:
System.Web.Http.dll中发生类型为"System.ArgumentNullException"的异常但未在用户代码中处理附加信息:值不能为null.
是因为Request
对象是null
.
解决方案是在测试中创建控制器的实例,例如:
var myApiController = new MyApiController
{
Request = new System.Net.Http.HttpRequestMessage(),
Configuration = new HttpConfiguration()
};
Run Code Online (Sandbox Code Playgroud)
这样,在创建类的新实例时,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);
}
}
Run Code Online (Sandbox Code Playgroud)
HttpRequestMessage
我认为发生的情况是,当您更新控制器时,您没有实例化或分配您的请求属性( )。我认为在通过单元测试调用 Api 方法之前必须指定请求。
您可能还需要配置 ( HttpConfiguration
):
sut = new YourController()
{
Request = new HttpRequestMessage {
RequestUri = new Uri("http://www.unittests.com") },
Configuration = new HttpConfiguration()
};
Run Code Online (Sandbox Code Playgroud)
让我知道这是否有效。