Model Class Validation Testing Using Nunit


A model class is an important component in every project. These classes mainly contain properties and validating these properties is a primary goal of developers.

We can enforce the validation by using Data Annotation validators. The advantage of using the Data Annotation validators is that they enable you to perform validation simply by adding one or more attributes – such as the Required or StringLength attribute etc. to a class property.

Before you can use the Data Annotation, you need "System.ComponentModel.DataAnnotations.dll assembly".

To find all the attributes related to data annotation, you can check the following Link. So here, we will learn how to check these property validations using Nunit Unit Test. Create a simple project and add the Nunit reference in this.

Now, ensure that all the tests will be shown in the Test Explorer. Add a referance of Nunit Test Adapter in the project.


Now, create an Employee model like this.

Here is the code snippet of the class.
  1. public class Employee    
  2.    {    
  3.        [Required(ErrorMessage ="Employee id shouldnot be Empty")]    
  4.        public string EmpId { get; set; }    
  5.        [Required(ErrorMessage ="Enter your Name")]    
  6.        public string EmpName { get; set; }    
  7.        public string Location { get; set; }    
  8.        public string Department { get; set; }    
  9.        [Required(ErrorMessage ="Enter your Email.")]    
  10.        [DataType(DataType.EmailAddress,ErrorMessage ="Please enter a valid Email Address.")]    
  11.        public string Email { get; set; }    
  13.        public int age { get; set; }    
  15.    }    
So here, we have added all the Data Annotation Rules. Now, create a new class to check the validation rules or attribute implemented in this model.

Add the following code in this.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5. using System.Threading.Tasks;    
  6. using System.ComponentModel.DataAnnotations;    
  8. namespace CalculatorTestProject    
  9. {    
  10.     public class CheckPropertyValidation    
  11.     {    
  12.         public  IList<ValidationResult> myValidation(object model)    
  13.         {    
  14.             var result = new List<ValidationResult>();    
  15.             var validationContext = new ValidationContext(model);    
  16.             Validator.TryValidateObject(model, validationContext, result);    
  17.             if (model is IValidatableObject) (model as IValidatableObject).Validate(validationContext);    
  19.                 return result;    
  23.         }    
  24.     }    
  25. }    
So, let's check what ValidationResult is.

ValidationResult is a class that comes under "System.ComponentModel.DataAnnotations" Namespace. If we go to its definition, we will find these methods inside these.

Validation Context describes the context on which validation is performed. It accepts a parameter as an object on which validation is performed. After that, the Validator.TryValidateObject checks for the validation against the attribute and updates the result.

Now, after implementing these things, write a unit test method to validate your class properties.
  1. using NUnit.Framework;    
  2. using System;    
  3. using System.Collections.Generic;    
  4. using System.Linq;    
  5. using System.Text;    
  6. using System.Threading.Tasks;    
  8. using Moq;    
  12. namespace CalculatorTestProject    
  13. {    
  14.     [TestFixture]    
  15.     public class CalculatorTestMethods    
  16.     {    
  17.         [Test]    
  18.        public void verifyclassattributes()    
  19.         {    
  20.             CheckPropertyValidation cpv = new CheckPropertyValidation();    
  21.             var emp = new Employee    
  22.             {    
  23.                EmpId="EID001",    
  24.                 EmpName="Krishna",    
  25.                 Location="Bangalore",    
  26.                 age=26,    
  27.                 Email="[email protected]"    
  29.             };    
  30.             var errorcount = cpv.myValidation(emp).Count();    
  31.             Assert.AreEqual(0, errorcount);    
  34.         }    
  35.     }    
  36. }  
Here is the test case.

Now, as I have created a valid class object, I am checking if the class properties are valid as per the validation attribute implemented on the model it simply passes. So, just run the Test Case.

Now, let's put an invalid data and check. Now, I am commenting the EmployeeId which is required as per the Model validation and let's see what will happen.
  1. [TestFixture]    
  2.   public class CalculatorTestMethods    
  3.   {    
  4.       [Test]    
  5.      public void verifyclassattributes()    
  6.       {    
  7.           CheckPropertyValidation cpv = new CheckPropertyValidation();    
  8.           var emp = new Employee    
  9.           {    
  10.             // EmpId="EID001",  (Employee Id Is commented)  
  11.               EmpName="Krishna",    
  12.               Location="Bangalore",    
  13.               age=26,    
  14.               Email="[email protected]"    
  16.           };    
  17.           var errorcount = cpv.myValidation(emp).Count();    
  18.           Assert.AreEqual(0, errorcount);    
  21.       }    
  22.   }    
Now, save the changes and debug the Test Case.

It will return the error and thus the Test Case will fail.


Thus, in this way, we can check or verify our model class property using Nunit. If you have any doubt, please let me know so that I can try to explain and modify it.

Up Next
    Ebook Download
    View all
    View all