Umut Esen Umut Esen - 7 days ago 6
C# Question

C# Unit Testing MVC Controller Action Parameter for Null value

Is it worth testing an MVC Controller action parameter for

null
values? The purpose is to ensure valid values are passed to the action and I guess
null
is also a possibility.

Here is the controller action:

[HttpPost]
public ActionResult Create(ContactViewModel viewModel)
{
if (!ModelState.IsValid)
return View("Create", viewModel);

if (viewModel == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "No data received");

var contact = Mapper.Map<Contact>(viewModel);

//contact.UserId = User.Identity.GetUserId();
contact.UserId = _user.Id;

_unitOfWork.Contacts.Add(contact);

_unitOfWork.Complete();

return RedirectToAction("Index");
}


And my test for checking the null parameter:

[TestMethod]
public void CreatePost_NullViewModelPassed_ShouldReturnBadRequest()
{
var result = _controller.Create(null) as HttpStatusCodeResult;
result.StatusCode.Should().Be(400);
}


The above test always passes, but, is this a useful test? I have been trying to hit the post method with Postman but I get the
HttpGet
version of my
Create
action:

public ViewResult Create()
{
return View("Create", new ContactViewModel());
}

Answer

The tests you're writing should give confidence of the system under test, but also raise bugs where possible to be resolved. If you have no null checking in your Create method then it is a very valid test to ensure the system doesn't just "die" when it receives a null value, instead it should respond accordingly which it seems to be doing by retrieving a status code of 400 (Bad Request), so overall I'd say the test is very valid - particularly where you may refactor in the future to introduce something such as the a repository/services pattern.

The tests for the Create method should cover all angles, not just successful and unsuccessful calls, but calls with various values in your view model, and just about any combination that could change the logic - such as booleans wrapped in conditionals.

Alas, if you want to hit the Post method in Postman then be sure to change the METHOD to POST just before the URL.

Comments