21

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.

7
  • 1
    Shouldn't controller.TestModel(new Model()); be controller.Post(new Model()); Aug 9, 2018 at 18:10
  • 2
    I don't know where you read the non-sense of 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 that ModelState.IsValid within the controller action isn't necessary and the validation action filter returns the appropriate "problem details" (also 2.1 feature)
    – Tseng
    Aug 9, 2018 at 20:02
  • Read ASP.NET Core 2.1.0-preview1: Improvements for building Web APIs to learn more details about it
    – Tseng
    Aug 9, 2018 at 20:02
  • I updated the code to fix the wrong function call . Thanks Marcus for the tip.
    – Alen Alex
    Aug 10, 2018 at 4:35
  • @Tseng This works fine with ModelState.IsValid when I deploy the application. The concern is when I unit test, ModelState.IsValid always returns true. It does not actually perform the model validations, which is where TryValidateModel(model) comes in, which is expected to forcefully validate. But, it is throwing Null Reference Exception for me.
    – Alen Alex
    Aug 10, 2018 at 4:43

4 Answers 4

14

It's configuration/integration issue.

You can see some additional info in the issue in ASP.NET Core repo and another one on github. But I can tell you the easiest fix (I used it once)

        var objectValidator = new Mock<IObjectModelValidator>();
        objectValidator.Setup(o => o.Validate(It.IsAny<ActionContext>(), 
                                          It.IsAny<ValidationStateDictionary>(), 
                                          It.IsAny<string>(), 
                                          It.IsAny<Object>()));
        controller.ObjectValidator = objectValidator.Object;
2
  • 4
    I'm not sure that's what the OP is asking for, as it effectively always passes. If I get the op right he wants to test the validation itself
    – Tseng
    Aug 9, 2018 at 19:57
  • Yes, this is basically mocking the validation which will always be true. The OP wasn't asking for this, see his answer below.
    – Akos
    Aug 16, 2019 at 7:57
4

As I figured how to fix Null Reference Exception thanks to @Egorikas, I noticed that it still doesn't actually validate the model and always returns a true.

I found that we could just use Validator class in System.ComponentModel.DataAnnotationsnamespace.

[TestMethod]
public void TestMethod1()
{
    var model = new Person();
    var validationResultList = new List<ValidationResult>();


    bool b1 = Validator.TryValidateObject(model, new ValidationContext(model), validationResultList);
}

You can directly validate it from the Test method itself, rather than having to call the controller, if ModelState validation is your intention.

Hope this helps.

5
  • 2
    This doesn't work for me. It will still return true :( Aug 5, 2019 at 8:49
  • @PresidentCamacho I got it to work for me for anything that would cause my API to return a 400. Could you give a little more information like what sort of properties are decorated with what sort of validation attributes?
    – Micteu
    Aug 15, 2019 at 16:26
  • 1
    One important note here, that the validation is not recursive, meaning only the top level is validated this way. Let's say there is a complex type Address in Person and you want to validate that this way, you need another line like: bool b2 = Validator.TryValidateObject(model.Address, new ValidationContext(model.Address), validationResultList);
    – Akos
    Aug 16, 2019 at 8:07
  • @Akos yes I noticed that :) Aug 16, 2019 at 8:32
  • To have it validate all properties and attributes. Add a true as last parameter to TryValidateObjet. Like so: Validator.TryValidateObject(model, new ValidationContext(model), validationResultList, true);
    – K Smith
    Jun 1 at 13:39
4

Based on Andrew Van Den Brink answer's, but with actually having the validation errors set in the ModelState.

private class ObjectValidator : IObjectModelValidator
{

    public void Validate(ActionContext actionContext, ValidationStateDictionary validationState, string prefix, object model)
    {
        var context = new ValidationContext(model, serviceProvider: null, items: null);
        var results = new List<ValidationResult>();

        bool isValid = Validator.TryValidateObject(
            model, context, results,
            validateAllProperties: true
        );

        if (!isValid)
            results.ForEach((r) =>
            {
                // Add validation errors to the ModelState
                actionContext.ModelState.AddModelError("", r.ErrorMessage);
            });
    }
}

Then, simply set the ObjectValidator in your controller:

controller.ObjectValidator = new ObjectValidator();
1
  • Works for me. Model that the controller tries to validate is actually validated using the validation logic in the app. Oct 28, 2020 at 14:55
0
public class ObjectValidator : IObjectModelValidator
    {
        private object parameter;
        public ObjectValidator(object parameter)
        {
            this.parameter = parameter;
        }
        public void Validate(ActionContext actionContext, ValidationStateDictionary validationState, string prefix, object model)
        {                
            var validationContext = new ValidationContext(parameter, null, null);
            System.ComponentModel.DataAnnotations.Validator.ValidateObject(model, validationContext);                
        }
    }

var model=new {}; // Model to test    
Controller controller = new Controller(); //Controller to test
controller.ObjectValidator = new ObjectValidator(model);

This one will throw exception

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.