Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Model Class Validation Testing Using NUnit

DZone's Guide to

Model Class Validation Testing Using NUnit

Learn how to debug and verify a model class property in C# using the NUnit unit testing framework.

· Performance Zone ·
Free Resource

Sensu is an open source monitoring event pipeline. Try it today.

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 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, to a class property.

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

To find all the attributes related to data annotation, you can check this link. Here, we will learn how to check these property validations using NUnit unit tests. Create a simple project and add the NUnit reference.

Image title

Now, ensure that all the tests will be shown in the Test Explorer. Add a reference of NUnit Test Adapter into the project.

Image title

Now, create an Employee model, like this.

Image title

Here is the code snippet of the class:

public class Employee    
   {    
       [Required(ErrorMessage ="Employee id shouldnot be Empty")]    
       public string EmpId { get; set; }    
       [Required(ErrorMessage ="Enter your Name")]    
       public string EmpName { get; set; }    
       public string Location { get; set; }    
       public string Department { get; set; }    
       [Required(ErrorMessage ="Enter your Email.")]    
       [DataType(DataType.EmailAddress,ErrorMessage ="Please enter a valid Email Address.")]    
       public string Email { get; set; }    

       public int age { get; set; }    

   }  

Here, we have added all the Data Annotation rules. Now, create a new class to check the validation rules or attributes implemented in this model.
Image titleAdd the following code:

using System;    
using System.Collections.Generic;    
using System.Linq;    
using System.Text;    
using System.Threading.Tasks;    
using System.ComponentModel.DataAnnotations;    

namespace CalculatorTestProject    
{    
    public class CheckPropertyValidation    
    {    
        public  IList<ValidationResult> myValidation(object model)    
        {    
            var result = new List<ValidationResult>();    
            var validationContext = new ValidationContext(model);    
            Validator.TryValidateObject(model, validationContext, result);    
            if (model is IValidatableObject) (model as IValidatableObject).Validate(validationContext);    

                return result;    



        }    
    }    
}    


Let's check what ValidationResult is.

ValidationResult is a class that falls under the "System.ComponentModel.DataAnnotations" namespace. If we go to its definition, we will find these methods:

Image title

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.

using NUnit.Framework;    
using System;    
using System.Collections.Generic;    
using System.Linq;    
using System.Text;    
using System.Threading.Tasks;    

using Moq;    



namespace CalculatorTestProject    
{    
    [TestFixture]    
    public class CalculatorTestMethods    
    {    
        [Test]    
       public void verifyclassattributes()    
        {    
            CheckPropertyValidation cpv = new CheckPropertyValidation();    
            var emp = new Employee    
            {    
               EmpId="EID001",    
                EmpName="Krishna",    
                Location="Bangalore",    
                age=26,    
                Email="krishna@gmail.com"    

            };    
            var errorcount = cpv.myValidation(emp).Count();    
            Assert.AreEqual(0, errorcount);    


        }    
    }    
}  

Here is the test case:

Image title

Now, let's put in invalid data and check. Now I am commenting the EmployeeId, which is required as per the Model validation. Let's see what will happen.

[TestFixture]    
  public class CalculatorTestMethods    
  {    
      [Test]    
     public void verifyclassattributes()    
      {    
          CheckPropertyValidation cpv = new CheckPropertyValidation();    
          var emp = new Employee    
          {    
            // EmpId="EID001",  (Employee Id Is commented)  
              EmpName="Krishna",    
              Location="Bangalore",    
              age=26,    
              Email="krishna@gmail.com"    

          };    
          var errorcount = cpv.myValidation(emp).Count();    
          Assert.AreEqual(0, errorcount);    


      }    
  }    

Now, save the changes and debug the test case.

Image title

Image title

Conclusion

In this way, we can verify our model class property using NUnit. If you have any doubts, please let me know so that I can try to explain and modify it.

Sensu: workflow automation for monitoring. Learn more—download the whitepaper.

Topics:
c# ,nunit ,validation ,tutorial ,performance

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}