c# - 如何将单元测试添加到我的流利验证类中?

标签 c# unit-testing fluentvalidation

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

我想知道如何为我的验证器类添加单元测试,以便我可以测试“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();
  }
}

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

关于c# - 如何将单元测试添加到我的流利验证类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51843923/

相关文章:

c# - GetShortPathNameA 在 C# 中不起作用

unit-testing - 在Visual Studio测试中,如何制作自动排除某些测试的播放列表?

c# - 使用 FluentValidation 验证互斥字段

c# - FluentValidation LogOnFailure 覆盖

c# - 自动将查询字符串从页面请求附加到 ASp.NET WebForms 中的出站页面请求

c# - 如何获得对 Sql Compact 数据库的权限?

c# - 试图读取或写入 protected 内存 - Sql Compact 和 .NEt

c# - 我是否必须在单元测试中伪造一个值对象

asp.net-mvc - 使用数据对 ASP.NET MVC 进行单元测试

c# - FluentValidation 调用规则集和通用规则