How to Write Unit Test Case in Nunit for Model Validation ?

Model Validation is very important aspects of any application because if you are sending or receiving the data that is not validated or not upto the decided standards then it will lead the data corruption in database. For model validation we used DataAnotations in model classes and according to that we displays the error messages to end users but this is not the tested code. We need to write the Test cases for varifies the behaviour of model classes with incorrect and correct data, so here we are using the NUnit framework for writting the test cases , below is the step by step implementation of test methods.

Create a Core MVC Project and Add a Nunit Test project into the solution explorer as like shown in below image.

Image is not available

As Shown in above image I have created one Core MVC Project named it NunitExampleMVC and also added one Nunit test project named it TestProj1 and in MVC Core Project models folder I have created on Product Model Class and define the properties with DataAnnotations. Created one class for validation checks and named it DataValidationChecks and have wriiten some custom code inside it.

Create a Product Model Class as shown in below image and code.

Image is not available
                    
  public class Product
    {
        [Required(ErrorMessage ="Id Should not be empty")]
        public int Id { get; set; }
        [Required(ErrorMessage = "Name Should not be empty")]
        public string Name { get; set; }
        public string Description { get; set; }
        [Required(ErrorMessage = "Price Should not be empty")]
        public int Price { get; set; }
        [Required(ErrorMessage = "ImageUrl Should not be empty")]
        public string ImageUrl { get; set; }
    }

Create a Custom Class for validation checks and write a method inside it as shown in below image and code.

Image is not available

In the below code I have created a class and named it DataValidationChecks and inside the code I have created one method that is ModelValidations taking one parameter as object and retruning the ILIST of ValidationResult ,is the inbuild class into the ComponentModel. After that I have created one object for ValidationContext and passed the model object into it. I have used Validator and TryValidateObject() method for validations and again checked this into the if condition and retrun the object of IList of ValidationResult.

                    
public class DataValidationChecks
{
 public  IList
     ModelValidations(object modelObject)
    {
    var validationResultObject=
    new List();
    var validationContext = new 
    ValidationContext(modelObject);
   Validator.TryValidateObject(modelObject, 
  validationContext,validationResultObject);
  if (modelObject is 
  IValidatableObject validatableModel)
  validationResultObject.AddRange
  (validatableModel.Validate(validationContext));
  return validationResultObject;
    }
}
Image is not available

For writting the Test cases , I have taken two scenarios one is for correct input data in model class and other one is incorrect input data for the model class and for this purpose written two seperate methods as shown in below code. Test_Verify_Model_Attributes() method is checking for correct data and it is getting passed but in Test_Verify_Model_Attributes_With_Null() method I am assigning some null values for required feilds so that it will geenarte the error and based on the error count it will fails the test as shown in below two images.

                    
 [TestFixture]
    public class ProductClassTestMethods
    {
        [Test]
        public void Test_Verify_Model_Attributes()
        {
            DataValidationChecks obj = new DataValidationChecks();
            var product = new Product
            {
                Id=1,
                Name="Laptop",
                Description="I7 Intel Processor",
                Price=54000,
                ImageUrl="https://placehold.jp/400*400"
            };
            var errorsCount=obj.ModelValidations(product).Count();
            Assert.AreEqual(0, errorsCount);
        }
        [Test]
        public void Test_Verify_Model_Attributes_With_Null()
        {
            DataValidationChecks obj = new DataValidationChecks();
            var product = new Product
            {
                //Id = 1,
               // Name = "Laptop",
                Description = "I7 Intel Processor",
                Price = 54000,
                ImageUrl = "https://placehold.jp/400*400"
            };
            var errorsCount = obj.ModelValidations(product).Count();
            Assert.AreEqual(0, errorsCount);
        }
    }
Image is not available
Image is not available

Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.