DEV Community

Cover image for SparkyTestHelpers: DataAnnotations
Brian Schroer
Brian Schroer

Posted on

SparkyTestHelpers: DataAnnotations

NuGet package | Source code | API documentation

This NuGet package contains helper classes to enable unit testing of .NET models and entities that use System.ComponentModel.DataAnnotations ValidationAttributes and/or validation via IValidatableObject.Validate(), via a fluent syntax.

Validation is initialized via the static Validation.For(obj) method:

using SparkyTestHelpers.DataAnnotation;
. . .
    var foo = new Foo { /* populated with valid values */ };
    ValidationForModel<Foo> validation = Validation.For(foo);
Enter fullscreen mode Exit fullscreen mode

The .ValidationResults() method validates the object and returns the results:

IEnumerable<ValidationResult> validationResults = Validation.For(foo).ValidationResults();
Enter fullscreen mode Exit fullscreen mode

…but you’ll usually check validation results via other fluently-composed methods:

Validation.For(foo).ShouldReturn.NoErrors();
Enter fullscreen mode Exit fullscreen mode

The When(expression) method arranges entity adjustments to be tested. (It makes a “clone” of the instance passed to Validation.For() before making adjustments, so each “When” call starts fresh with the original values):

Validation.For(foo)
    .When(x => x.Bar = null)
    .ShouldReturn.RequiredErrorFor(x => x.Bar);
Enter fullscreen mode Exit fullscreen mode

A code example above shows a call to .ShouldReturn.NoErrors() to assert that the model has no validation errors.

.ShouldReturn.ErrorFor() is used to assert that a specific validation error was returned:

Validation.For(foo)
    .When(x => x.Bar = "13")
    .ShouldReturn.ErrorFor(x => x.Bar)
    .WithMessage("Invalid Bar value. 13 is unlucky!");

// Multi-member validation result:
Validation.For(foo)
    .When(x => 
    { 
        x.Bar = "dog";
        x.Baz = "cat";
    })
    .ShouldReturn.ErrorFor(x => x.Bar).AndFor(x => x.Baz)
        .WithMessage("Invalid Bar/Baz combination.");
Enter fullscreen mode Exit fullscreen mode

ShouldReturn.ErrrorFor(expression).ForValidationAttribute<TAttribute> is used to assert that a ValidationResult was created by a specific ValidationAttribute:

Validation.For(foo)
    .When(x => x.Bar = null)
    .ShouldReturn.ErrorFor(x => x.Bar).ForValidationAttribute<RequiredAttribute>();
Enter fullscreen mode Exit fullscreen mode

There are also ShouldReturn. methods for standard ValidationAttributes:

  • [CreditCard]: ShouldReturn.CreditCardErrorFor(x => x.Foo);
  • [EmailAddress]: ShouldReturn.EmailAddressErrorFor(x => x.Foo);
  • [EnumDataType]: ShouldReturn.EnumDataTypeErrorFor(x => x.Foo);
  • [MaxLength]: ShouldReturn.MaxLengthErrorFor(x => x.Foo);
  • [MinLength]: ShouldReturn.MinLengthErrorFor(x => x.Foo);
  • [Phone]: ShouldReturn.PhoneErrorFor(x => x.Foo);
  • [Range]: ShouldReturn.RangeErrorFor(x => x.Foo);
  • [RegularExpression]: ShouldReturn.RegularExpressionErrorFor(x => x.Foo);
  • [Required]: ShouldReturn.RequiredErrorFor(x => x.Foo);
  • [StringLength]: ShouldReturn.StringLengthErrorFor(x => x.Foo);

You don’t have to specify the expected error message for the .ForValidationAttribute method or for the methods listed above. The validation tester automatically determines the error message from the attribute.


Happy Testing!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️