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
Please enter at least three characters to search
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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Driving DevOps With Smart, Scalable Testing
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • Practical Use of Weak Symbols
  • Generate Unit Tests With AI Using Ollama and Spring Boot

Trending

  • Infrastructure as Code (IaC) Beyond the Basics
  • Designing a Java Connector for Software Integrations
  • Memory-Optimized Tables: Implementation Strategies for SQL Server
  • When Airflow Tasks Get Stuck in Queued: A Real-World Debugging Story
  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.6K 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

  • Driving DevOps With Smart, Scalable Testing
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • Practical Use of Weak Symbols
  • Generate Unit Tests With AI Using Ollama and Spring Boot

Partner Resources

×

Comments
Oops! Something Went Wrong

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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!