我有一个模型(下面的示例),并希望使用MOQ进行验证。
public class Employee{
public string FirstName {get;set;}
public string LastName {get;set;}
}
想运行以下测试用例
说实话,我对MOQ一无所知,因此没有尝试任何选项。
答案 0 :(得分:1)
Moq用于单元测试,它用于将fack实例模拟到测试对象下的系统,
您可以通过实施IValidatableObject
,
尝试下面的代码段,
public class Employee : IValidatableObject
{
public string FirstName { get; set; }
public string LastName { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (string.IsNullOrEmpty(FirstName) || FirstName.Length > 50) {
results.Add(new ValidationResult("Invalid first Name"));
}
if (string.IsNullOrEmpty(LastName) || LastName.Length > 50)
{
results.Add(new ValidationResult("Invalid last Name"));
}
return results;
}
}
验证对象,
var toValidate = new Employee(){};
var results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(
toValidate,
new ValidationContext(toValidate, null, null),
results,
true);