How can I unit test my custom validation attribute

Your attribute EligabilityStudentDebtsAttribute is just a standard class, like everything else, just unit test the IsValid() method. If it works OK, trust to Framework that attribute works OK.

So:

[Test]
public void AttibuteTest()
{
   // arrange
   var value = //.. value to test - new Eligability() ;
   var attrib = new EligabilityStudentDebtsAttribute();

   // act
   var result = attrib.IsValid(value);

   // assert
   Assert.That(result, Is.True)
}

I have found out that IsValid does not work well on simple types like string. E.g. if you have a validation on a string query parameter that is not an object. Additionally it's easier to test a value directly on the attribute without having to provide a whole object. It also allows to check the error message. This is how it works:

string input = "myteststring";
var myAttribute = new MyAttribute()
var result = attribute.GetValidationResult(input, new ValidationContext(input));

var isSuccess = result == ValidationResult.Success;
var errorMessage = result?.ErrorMessage;

This code tests only the validation of your input value and nothing else.

P.S. I have tested this in dotnet core, but I would think this works for ordinary dotnet as well.


Your custom validation attribute might be dependent on the state of other properties. In this case you can use the System.ComponentModel.DataAnnotations.Validator static methods, for example:

var model = ...
var context = new ValidationContext(model);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(model, context, results, true);
Assert.True(isValid);