我有一个看起来像这样的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个字符?
答案 0 :(得分:2)
您可以使用以下类似方法(使用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以下为有效。
答案 1 :(得分:0)
使用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"));
}