gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:15:47 26 4
gpt4 key购买 nike

我有一个看起来像这样的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com