猿问

如何将单元测试添加到我的流畅验证类中?

我有 ac# 模型类(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 个字符?


慕姐8265434
浏览 197回答 2
2回答

HUH函数

您可以使用以下内容(这使用 xunit,根据您的首选框架进行调整)public class AddressValidationShould{&nbsp; private AddressValidator Validator {get;}&nbsp; public AddressValidationShould()&nbsp; {&nbsp; &nbsp; Validator = new AddressValidator();&nbsp; }&nbsp; [Fact]&nbsp; public void NotAllowEmptyPostcode()&nbsp; {&nbsp; &nbsp; var address = new Address(); // You should create a valid address object here&nbsp; &nbsp; address.Postcode = string.empty; // and then invalidate the specific things you want to test&nbsp; &nbsp; Validator.Validate(address).IsValid.Should().BeFalse();&nbsp; }}...显然创建其他测试来涵盖应该/不应该允许的其他事情。比如AddressLine140以上无效,40以下有效。

慕婉清6462132

使用 MSTest,您可以编写[TestMethod]public void NotAllowEmptyPostcode(){&nbsp; &nbsp; // Given&nbsp; &nbsp; var address = new Address(); // You should create a valid address object here&nbsp; &nbsp; address.Postcode = string.empty; // invalidate the specific property&nbsp; &nbsp; // When&nbsp; &nbsp; var result = validator.Validate(address);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // Then (Assertions)&nbsp; &nbsp; Assert.That(result.Errors.Any(o => o.PropertyName== "Postcode"));}
随时随地看视频慕课网APP
我要回答