ValueSourceAttribute
ValueSourceAttribute indicates the source to be used to
provide data for one parameter of a test method.
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using System;
using System.Collections;
using System.Reflection;
namespace NUnit.Framework
{
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)]
public class ValueSourceAttribute : DataAttribute, IParameterDataSource
{
private readonly string sourceName;
private readonly Type sourceType;
public string SourceName => sourceName;
public Type SourceType => sourceType;
public ValueSourceAttribute(string sourceName)
{
this.sourceName = sourceName;
}
public ValueSourceAttribute(Type sourceType, string sourceName)
{
this.sourceType = sourceType;
this.sourceName = sourceName;
}
public IEnumerable GetData(ParameterInfo parameter)
{
return GetDataSource(parameter);
}
private IEnumerable GetDataSource(ParameterInfo parameter)
{
Type reflectedType = sourceType;
if (reflectedType == (Type)null)
reflectedType = parameter.Member.ReflectedType;
if (sourceName == null)
return Reflect.Construct(reflectedType) as IEnumerable;
MemberInfo[] member = reflectedType.GetMember(sourceName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (member.Length == 1) {
MemberInfo memberInfo = member[0];
object obj = Reflect.Construct(reflectedType);
FieldInfo fieldInfo = memberInfo as FieldInfo;
if (fieldInfo != (FieldInfo)null)
return (IEnumerable)fieldInfo.GetValue(obj);
PropertyInfo propertyInfo = memberInfo as PropertyInfo;
if (propertyInfo != (PropertyInfo)null)
return (IEnumerable)propertyInfo.GetValue(obj, null);
MethodInfo methodInfo = memberInfo as MethodInfo;
if (methodInfo != (MethodInfo)null)
return (IEnumerable)methodInfo.Invoke(obj, null);
}
return null;
}
}
}