Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: Validating enums with a custom FluentValidator validator

$
0
0

Hi

I'm not entirely sure I understand the purpose of your custom validator. If you're validating a property whose value is of type DayOfWeek, then by its very definition it will already be within the range of values specified in the DayOfWeek enum, so there's no need for this validator. Or am I missing something?

To test a validator itself, simply create a validator class for a fake object and then feed it the data that should cause either validation to pass or fail, and assert the results. There are plenty of examples of this in FluentValidation's own test project - I'd suggest having a look at those as a starting point. Here's a simple example that tests the NotNull validator works as expected:

[TestFixture]
public class NotNullTester {
  
  public class Person {
    public string Surname { get; set; }
  }
  
  public class TestValidator : AbstractValidator<Person> {
  }


  [Test]
  public void NotNullValidator_should_pass_if_value_has_value() {
    var validator = new TestValidator();
    validator.RuleFor(x => x.Surname).NotNull();
    
    var result = validator.Validate(new Person{Surname = "Foo"});
    Assert.IsTrue(result.IsValid);
  }

  [Test]
  public void NotNullValidator_should_fail_if_value_is_null() {
    var validator = new TestValidator();
    validator.RuleFor(x => x.Surname).NotNull();
    
    var result = validator.Validate(new Person { Surname = null });
    Assert.IsFalse(result.IsValid);
  }
  
  // etc etc
}

Viewing all articles
Browse latest Browse all 1917

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>