这是我用于测试类型扩展方法的类的片段:
class Something
{
[StringLength(100, MinimumLength = 1, ErrorMessage = "Must have between 1 and 100 characters")]
public string SomePublicString { get; set; }
}
我有以下扩展方法:
public static class TypeExtensions
{
public static TAttributeType GetCustomAttribute<T, TAttributeType, TProperty>(this T value, Expression<Func<T, TProperty>> propertyLambda, bool inherit = false)
{
var type = typeof(T);
var member = (MemberExpression)propertyLambda.Body;
var propertyInfo = (PropertyInfo)member.Member;
var customAttributes = propertyInfo.GetCustomAttributes(typeof(TAttributeType), inherit);
return customAttributes.OfType<TAttributeType>().FirstOrDefault();
}
}
单元测试中的用法:
1: var something = new Something();
2: var actual = something.GetCustomAttribute<Something, StringLengthAttribute, string>(x => x.SomePublicString);
3: actual.MinimumLength.Should().Be(1);
4: actual.MaximumLength.Should().Be(100);
5: actual.ErrorMessage.Should().Be("Must have between 1 and 100 characters");
这将返回一个通过测试(使用 FluentAssertions)。
但是,我想在第 2 行中对 GetCustomAttribute() 的方法调用如下:
var actual = something.GetCustomAttribute<StringLengthAttribute>(x => x.SomePublicString);
这可能吗?我错过了什么吗?也许我正在喝咖啡因崩溃。:(