CRo*_*rts 2 c# unit-testing fluentvalidation
我有 ac# 模型类 (Address.cs),看起来像这样......
namespace myProject.Models
{
[Validator(typeof(AddressValidator))]
public class Address
{
public string AddressLine1 { get; set; }
public string PostCode { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个验证器类(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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道如何为我的验证器类添加单元测试,以便我可以测试“地址行 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();
}
}
Run Code Online (Sandbox Code Playgroud)
...并且显然创建其他测试来涵盖应该/不应该允许的其他事情。如AddressLine1超过40为无效,40以下为有效。
| 归档时间: |
|
| 查看次数: |
7948 次 |
| 最近记录: |