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