Data Annotations on record fails in unittest

Viewed 704

Currently we are setting up a new project and like to use the new records introduced in C# 9. We encounter a problem with DataAnnotations inside the record (constructor) not being triggered during the unittest.

Now the DataAnnotation is triggered when calling the Controller, but when i try to simulate this in a unittest (see code below) it will never return any errors.

        //Unit Testing ASP.NET DataAnnotations validation
        //http://stackoverflow.com/questions/2167811/unit-testing-asp-net-dataannotations-validation
        protected static IList<ValidationResult> ValidateModel(object model)
        {
            var validationResults = new List<ValidationResult>();
            var ctx = new ValidationContext(model, null, null);
            Validator.TryValidateObject(model, ctx, validationResults, true);
            return validationResults;
        }

Currently we created a workaround:

    public record FooRecord(string BarProperty)
    {
        [Required]
        public string BarProperty { get; init; } = BarProperty;

    }

But I'm hoping if someone knows why this happens and maybe know how to solve this using the shorthand syntax:

    public record FooRecord([Required] BarProperty){ }
1 Answers

It will work as expected if you define your record as:

public record FooRecord([property: Required] BarProperty){ }
Related