如何将单元测试添加到我的流利验证 class?

How to add unit tests to my fluent validation class?

我有一个 c# 模型 class (Address.cs) 看起来像这样...

namespace myProject.Models
{
    [Validator(typeof(AddressValidator))]
    public class Address
    {
        public string AddressLine1 { get; set; }
        public string PostCode { get; set; }
    }
}

我有一个验证器 class (AddressValidator.cs) 看起来像这样...

namespace myProject.Validation
{
    public class AddressValidator : AbstractValidator<Address>
    {
        public AddressValidator()
        {
            RuleFor(x => x.PostCode).NotEmpty().WithMessage("The Postcode is required");
            RuleFor(x => x.AddressLine1).MaximumLength(40).WithMessage("The first line of the address must be {MaxLength} characters or less");
        }
    }
}

我想知道如何为我的验证器 class 添加单元测试,这样我就可以测试 'Address Line 1' 最多需要 40 个字符?

你可以用类似下面的方法来做到这一点(这使用 xunit,调整到你喜欢的框架)

public class AddressValidationShould
{
  private AddressValidator Validator {get;}
  public AddressValidationShould()
  {
    Validator = new AddressValidator();
  }

  [Fact]
  public void NotAllowEmptyPostcode()
  {
    var address = new Address(); // You should create a valid address object here
    address.Postcode = string.empty; // and then invalidate the specific things you want to test
    Validator.Validate(address).IsValid.Should().BeFalse();
  }
}

...显然要创建其他测试来覆盖 should/shouldn 不允许的其他内容。如AddressLine1超过40无效,40以下有效。

借助 MSTest,您可以编写

[TestMethod]
public void NotAllowEmptyPostcode()
{
    // Given
    var address = new Address(); // You should create a valid address object here
    address.Postcode = string.empty; // invalidate the specific property

    // When
    var result = validator.Validate(address);
    
    // Then (Assertions)
    Assert.That(result.Errors.Any(o => o.PropertyName== "Postcode"));
}