I'm trying to write unit tests for ModelState validation for an Asp.Net Core Web API.
I read that, the best way to do so is to use TryValidateModel
function. But, every time I run the unit test, it throws NullReference exception.
I found many articles suggesting controller.ModelState.AddModelError("","")
, but I'm not interested in this, as I believe that it beats the actual purpose of the real model validation.
[TestMethod]
public void TestMethod1()
{
var controller = new TestController();
controller.Post(new Model());
}
public class TestController : Controller
{
public IActionResult Post(Model model)
{
bool b = TryValidateModel(model)
return Ok();
}
}
TryValidateModel(model)
always throws NullReference Exception from TryValidateModel(model, prefix)
function.
Appreciate any help.
TryValidateModel
being best practice, but thats definitely not true. First, all the official tutorials used (or still use)ModelState.IsValid
. Second, with ASP.NET Core 2.1 a new[ApiController]
attribute has been added, which reduces the number of things one has to do in WebApi-esque controllers. Among them, is that models implicitly validated, so thatModelState.IsValid
within the controller action isn't necessary and the validation action filter returns the appropriate "problem details" (also 2.1 feature) – AmbieModelState.IsValid
when I deploy the application. The concern is when I unit test,ModelState.IsValid
always returnstrue
. It does not actually perform the model validations, which is whereTryValidateModel(model)
comes in, which is expected to forcefully validate. But, it is throwing Null Reference Exception for me. – Dedra[ApiController]
, all of your logic within the controller and your unit tests based on it become obsolete, since in real word the action will never be called if there is a model validation error when using attributed based model validation (either by creating your own action attribute that checks the validation or by usingApiControllerAttribute
) – Ambie