DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Effective Engineering Feedback: Software Testing
  • The LLM Selection War Story: Part 2 - The Six LLM Failure Archetypes That Will Wreck Your Production System
  • Agentic Development: My Invisible Dev Team
  • Clean Code in the Age of Copilot: Why Semantics Matter More Than Ever

Trending

  • Production Database Migration or Modernization: A Comprehensive Planning Guide [Part 2]
  • We Went Multi-Cloud and Almost Drowned: Lessons From Running Across AWS, GCP, and Azure
  • The Invisible OOMKill: Why Your Java Pod Keeps Restarting in Kubernetes
  • How Retry Storms Crash API-Led Systems: Bounded Reliability Patterns for Distributed Architectures
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Model Class Validation Testing Using NUnit

Model Class Validation Testing Using NUnit

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

By 
Debendra Dash user avatar
Debendra Dash
·
Jun. 21, 18 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
6.7K Views

Join the DZone community and get the full member experience.

Join For Free

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="[email protected]"    

            };    
            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="[email protected]"    

          };    
          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.

NUnit unit test

Opinions expressed by DZone contributors are their own.

Related

  • Effective Engineering Feedback: Software Testing
  • The LLM Selection War Story: Part 2 - The Six LLM Failure Archetypes That Will Wreck Your Production System
  • Agentic Development: My Invisible Dev Team
  • Clean Code in the Age of Copilot: Why Semantics Matter More Than Ever

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook