Search code examples
c#exceptionfluentvalidation

Integrating FluentValidation validator with base Entity class


I want to use AbstractValidator<T> inside base entity class.

[Serializable]
public abstract class Entity<T> where T : Entity<T>
{
    public virtual Boolean Validate(AbstractValidator<T> validator)
    {
        return validator.Validate(this as ValidationContext<T>).IsValid;
    }
    // other stuff..
}

But one of my tests fails saying that Validate() method couldn't accept null as a paramter.

[Test]
public void CategoryDescriptionIsEmpty()
{
    var category = new Category
    {
        Title = "some title",
        Description = String.Empty
    };

    Assert.False(category.Validate(this.validator) == true);
}

[SetUp]
public void Setup()
{
    this.validator = new CategoryValidator();
}

I'm using Visual Web Developer and at the moment can't install C# Developer Express to create console application to debug the error. Since that I don't know how do I debug inside the unit test. Alternatively it would be great if some explanation could be given!

Thanks!


Solution

  • This topic is old, but I found useful and made a little diferent:

    public abstract class WithValidation<V> where V : IValidator
        {
    
            private IValidator v = Activator.CreateInstance<V>();
    
            public bool IsValid => !(Errors.Count() > 0);
    
            public IEnumerable<string> Errors
            {
                get
                {
                    var results = v.Validate(this);
    
                    List<string> err = new List<string>();
    
                    if (!results.IsValid)
                        foreach (var item in results.Errors)
                            err.Add(item.ErrorMessage);
    
                    return err;
    
                }
            }
        }
    
    public class Client : WithValidation<ClientValidator>
        {
    
            public Guid Id { get; set; }
    
            public string Name { get; set; }
    
            public int Age { get; set; }
    
        }
    
    public class ClientValidator : AbstractValidator<Client>
        {
    
            public ClientValidator()
            {
                RuleFor(c => c.Name).NotNull();
                RuleFor(c => c.Age).GreaterThan(10);
            }
    
    
        }
    

    So you can use easier now like:

    Client c = new Client();
    
    var isvalid = c.IsValid;
    
    IList<string> errors = c.Errors;