【问题标题】:How to add unit tests to my fluent validation class?如何将单元测试添加到我的流利验证类?
【发布时间】:2018-08-14 14:34:13
【问题描述】:

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

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

我有一个看起来像这样的验证器类 (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");
        }
    }
}

我想知道,如何为我的验证器类添加单元测试,以便我可以测试,例如,“地址第 1 行”最多占用 40 个字符?

【问题讨论】:

    标签: c# unit-testing fluentvalidation


    【解决方案1】:

    您可以通过以下方式做到这一点(这使用 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();
      }
    }
    

    ...并且显然创建其他测试来涵盖应该/不应该允许的其他事情。如AddressLine1大于40无效,小于等于40有效。

    【讨论】:

      【解决方案2】:

      使用 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"));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-07
        • 1970-01-01
        • 2017-07-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多