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

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Practical Use of Weak Symbols
  • Generate Unit Tests With AI Using Ollama and Spring Boot
  • Understanding the Two Schools of Unit Testing
  • Go: Unit and Integration Tests

Trending

  • Evolution of Cloud Services for MCP/A2A Protocols in AI Agents
  • A Complete Guide to Modern AI Developer Tools
  • How the Go Runtime Preempts Goroutines for Efficient Concurrency
  • A Guide to Developing Large Language Models Part 1: Pretraining
  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.5K 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="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.

NUnit unit test

Opinions expressed by DZone contributors are their own.

Related

  • Practical Use of Weak Symbols
  • Generate Unit Tests With AI Using Ollama and Spring Boot
  • Understanding the Two Schools of Unit Testing
  • Go: Unit and Integration Tests

Partner Resources

×

Comments

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: