扩展Object增加TryModelValidation方法,验证模型是否可以通过验证,并增加测试

This commit is contained in:
falcon 2022-11-24 10:58:46 +08:00
parent 0bae9c9943
commit 0faab483a9
2 changed files with 99 additions and 0 deletions

View File

@ -0,0 +1,76 @@
using Falcon.SugarApi.ModelValidation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace Falcon.SugarApi.Test
{
/// <summary>
/// Json序列化测试
/// </summary>
[TestClass]
public class ModelValidationTest
{
[TestMethod]
public void ValidateTest() {
TestModel model;
List<ValidationResult> results;
bool r;
model = new TestModel {
Age = "30",
Name = "Tom",
};
r = model.TryModelValidation(out results);
Assert.IsTrue(r);
Assert.IsTrue(results != null);
Assert.IsTrue(results.Count == 0);
model = new TestModel {
Age = "60",
};
r = model.TryModelValidation(out results);
Assert.IsFalse(r);
Assert.IsTrue(results.Count == 2);
model = new TestModel {
MaxLength = "111111111111111111",
Name = "Tom",
Age = "30",
};
r = model.TryModelValidation(out results);
Assert.IsFalse(r);
Assert.IsTrue(results.Count == 1);
model = new TestModel {
Name = "abc",
Age = "20",
IsIntProp = "abc",
MaxLength = "1",
};
r = model.TryModelValidation(out results);
Assert.IsFalse(r);
Assert.IsTrue(results.Count == 1);
Assert.IsTrue(results.First().MemberNames.First() == "IsIntProp");
}
/// <summary>
/// 测试用模型
/// </summary>
public class TestModel
{
[Required]
public string Name { get; set; }
[Range(10, 50)]
public string Age { get; set; }
[MaxLength(3)]
public string MaxLength { get; set; }
[IsInt]
public string IsIntProp { get; set; } = "123";
}
}
}

View File

@ -0,0 +1,23 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Falcon.SugarApi.ModelValidation
{
/// <summary>
/// 扩展对象验证方法
/// </summary>
public static class ObjectValidateExtend
{
/// <summary>
/// 尝试执行对象验证,返回验证结果
/// </summary>
/// <param name="model">要验证的模型</param>
/// <param name="results">验证结果</param>
/// <returns>通过验证True否则False</returns>
public static bool TryModelValidation(this object model, out List<ValidationResult> results) {
var context = new ValidationContext(model);
results = new List<ValidationResult>();
return Validator.TryValidateObject(model, context, results, true);
}
}
}