Writing Unit Test for Model Validation

It is a pretty common pattern to validate your Web Action model using ModelState.IsValid method. For example,

public async Task<UpdateUserProfileResponse> UpdateUser(UpdateUserProfileRequest user)
{
    if (ModelState.IsValid)
    {
        // Valid Model, do your job
    }
    else
    {
        // Send response indicating invalid model
    }
}

A pretty useful pattern, as it makes use of the DataAnnotations to validate and provide meaning messages. One question though that raises is, how do you unit test such a pattern ? The trick lies in emulating the ModelState. You could do with minimal code. For example,

protected void MockModelState<TModel,TController>(TModel model, TController controller) where TController: ControllerBase
{
    var validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(model, null, null);
    var validationResults = new List<ValidationResult>();
    Validator.TryValidateObject(model, validationContext, validationResults, true);
    foreach (var validationResult in validationResults)
    {
        controller.ModelState.AddModelError(validationResult.MemberNames.First(), validationResult.ErrorMessage);
    }
}

With that in place, you could now write Unit Test for your controller as the following

var userController = new UserController(Mapper, mockUserProfileService.Object, null, null);
MockModelState(request,userController);
var result = await userController.UpdateUser(request);

That’s all you need.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s