Last active
August 29, 2015 14:03
-
-
Save PureKrome/7712e64a690d0960d6e0 to your computer and use it in GitHub Desktop.
Fluent Validation with SetValidator should error when it doesn't.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using FluentValidation; | |
using FluentValidation.TestHelper; | |
using Xunit; | |
namespace FVSetValidatorTest | |
{ | |
#region Models | |
public class UnitOfMeasure | |
{ | |
public string Type { get; set; } | |
public decimal Value { get; set; } | |
} | |
public class LandDetails | |
{ | |
public UnitOfMeasure Area { get; set; } | |
public UnitOfMeasure Frontage { get; set; } | |
} | |
#endregion | |
#region Validator's | |
public class UnitOfMeasureValidator : AbstractValidator<UnitOfMeasure> | |
{ | |
public UnitOfMeasureValidator() | |
{ | |
RuleFor(unit => unit.Value).GreaterThanOrEqualTo(0); | |
RuleFor(unit => unit.Type).NotNull() | |
.When(unit => unit.Value > 0) | |
.WithMessage("If a unit of measure's 'Value' is provided, then a 'Type' also needs to be provided."); | |
} | |
} | |
public class LandValidator : AbstractValidator<LandDetails> | |
{ | |
public LandValidator() | |
{ | |
RuleFor(land => land.Area).SetValidator(new UnitOfMeasureValidator()); | |
RuleFor(land => land.Frontage).SetValidator(new UnitOfMeasureValidator()); | |
} | |
} | |
#endregion | |
public class LandValidatorFacts | |
{ | |
[Fact] | |
public void GivenANegativeValue_Validate_ShouldHaveAValidationError() | |
{ | |
var landDetails = new LandDetails | |
{ | |
Area = new UnitOfMeasure | |
{ | |
Value = -111 | |
} | |
}; | |
var validator = new LandValidator(); | |
validator.ShouldHaveChildValidator(land => land.Area, typeof(UnitOfMeasureValidator)); | |
// This line of code SHOULD pass, but it doesn't because the validation doesn't error. | |
validator.ShouldHaveValidationErrorFor(land => land.Area, landDetails.Area); | |
// This works.... | |
var results = validator.Validate(landDetails); | |
Assert.Equal(1, results.Errors.Count); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment