c#中验证属性的单元测试
本文关键字:单元测试 属性 验证 | 更新日期: 2023-09-27 18:25:25
我试图使用Validator在c#模型上进行验证的单元测试,但它不适用于NewtonSoft属性。
这是我的单元测试:
var searchController = new SearchController();
var requestModel = new RequestModel
{
Id = "23456",
MobileNumber = "9876543210"
};
var results = new List<ValidationResult>();
var context = new ValidationContext(requestModel, null, null);
var isvalid = Validator.TryValidateObject(requestModel, context, results,true);
Assert.IsFalse(isvalid);
这是我的模型:
public class XYZ
{
[JsonProperty("mobileNumber")]
[MinLength(3, ErrorMessage = "MOBILENUMBER_LENGTH_MIN")]
public string MobileNumber { get; set; }
[JsonProperty("refNumber")]
[MinLength(3, ErrorMessage = "REFNUMBER_LENGTH_MIN")]
public string RefNumber { get; set; }
[JsonProperty("subscriberFirstName")]
[MinLength(3, ErrorMessage = "FIRSTNAME_LENGTH_MIN")]
public string FirstName { get; set; }
}
有人能帮我吗?
改编Jon Davis关于单元测试ASP.NET DataAnnotations验证的回答
如果你有这样的课程:
public class Person
{
[MinLength(3, ErrorMessage = "FIRSTNAME_LENGTH_MIN")]
public string FirstName { get; set; }
[MinLength(3, ErrorMessage = "MOBILENUMBER_LENGTH_MIN")]
public string MobileNumber { get; set; }
}
您可以这样测试验证结果:
[TestMethod]
public void ModelValidationFailsWithInvalidLength()
{
// arrange
var myPerson = new Person()
{
FirstName = "Hi",
MobileNumber = "12"
};
// act
var validationResults = ValidateModel(myPerson);
// assert
Assert.IsTrue(validationResults.Any(
v => v.MemberNames.Contains(nameof(Person.FirstName)) &&
v.ErrorMessage.Contains("FIRSTNAME_LENGTH_MIN")));
}
private IList<ValidationResult> ValidateModel(object model)
{
var validationResults = new List<ValidationResult>();
var ctx = new ValidationContext(model, null, null);
Validator.TryValidateObject(model, ctx, validationResults, true);
return validationResults;
}