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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Testing Business Programs Without Constructing Domain Objects
  • Why Standard Test Automation Misses the Failures That Matter in AI Agent Systems
  • More Tests, More Confidence? Test Suites Are Investment Portfolios
  • One of Waterfall's Most Resilient Artifacts

Trending

  • Building a Real Pipeline With senro: Monorepos, Caching, and Triggers
  • Kill the Worker, Keep the Research: Build a Recoverable LangGraph Agent on Temporal
  • The Twelve-Factor Agents: Building Production-Ready LLM Applications
  • Vision-Language Models in 2026: From Research Breakthroughs to Cloud-Native Production Systems

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Jun. 21, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
6.9K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Testing Business Programs Without Constructing Domain Objects
  • Why Standard Test Automation Misses the Failures That Matter in AI Agent Systems
  • More Tests, More Confidence? Test Suites Are Investment Portfolios
  • One of Waterfall's Most Resilient Artifacts

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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