text 模型DataAnnotation测试
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text 模型DataAnnotation测试相关的知识,希望对你有一定的参考价值。
Model:
public class OrganisationVM
{
public int Id { get; set; }
[Required]
[MinLength(5, ErrorMessage = "Must be at least 5 characters long")]
public string Name { get; set; }
[Required]
[Range(1, 100000, ErrorMessage = "Must be greater than 1 and less than 1000000")]
public int Employees { get; set; }
}
XUnitTest:
public class OrganisationVMTest
{
[Fact]
public void OrganisationVMValid()
{
// Arrange
var model = new OrganisationVM
{
Id = 1,
Name = "Julian",
Employees = 1000
};
var context = new ValidationContext(model, null, null);
var result = new List<ValidationResult>();
// Act
var valid = Validator.TryValidateObject(model, context, result, true);
Assert.True(valid);
}
[Fact]
public void OrganisationVM_name_required()
{
// Arrange
var model = new OrganisationVM
{
Id = 1,
Employees = 1000
};
var context = new ValidationContext(model, null, null);
var result = new List<ValidationResult>();
// Act
var valid = Validator.TryValidateObject(model, context, result, true);
Assert.False(valid);
var failure = Assert.Single(
result,
x => x.ErrorMessage == "The Name field is required.");
Assert.Single(failure.MemberNames, x => x == "Name");
}
[Fact]
public void OrganisationVM_Name_Short()
{
// Arrange
var model = new OrganisationVM
{
Id = 1,
Name = "July",
Employees = 1000
};
var context = new ValidationContext(model, null, null);
var result = new List<ValidationResult>();
// Act
var valid = Validator.TryValidateObject(model, context, result, true);
Assert.False(valid);
var failure = Assert.Single(
result,
x => x.ErrorMessage == "Must be at least 5 characters long");
Assert.Single(failure.MemberNames, x => x == "Name");
}
[Fact]
public void OrganisationVM_Employee_Range()
{
// Arrange
var model = new OrganisationVM
{
Id = 1,
Name = "Julian",
Employees = 0
};
var context = new ValidationContext(model, null, null);
var result = new List<ValidationResult>();
// Act
var valid = Validator.TryValidateObject(model, context, result, true);
Assert.False(valid);
var failure = Assert.Single(
result,
x => x.ErrorMessage == "Must be greater than 1 and less than 1000000");
Assert.Single(failure.MemberNames, x => x == "Employees");
}
[Fact]
public void OrganisationVM_Employee_Required()
{
// Arrange
var model = new OrganisationVM
{
Id = 1,
Name = "Julian"
};
var context = new ValidationContext(model, null, null);
var result = new List<ValidationResult>();
// Act
var valid = Validator.TryValidateObject(model, context, result, true);
Assert.False(valid);
}
}
以上是关于text 模型DataAnnotation测试的主要内容,如果未能解决你的问题,请参考以下文章
csharp 创建dataannotation dynamic.cs
DataAnnotation 不显示存储在 ViewModel 中的数据