Skip to content

Instantly share code, notes, and snippets.

@gshutler
Created April 15, 2010 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gshutler/367226 to your computer and use it in GitHub Desktop.
Save gshutler/367226 to your computer and use it in GitHub Desktop.
Extension method for setting non-public properties in tests
public static class ObjectSetterExtensions
{
public static TValue SetProperty<T, TValue>(this T target, Expression<Func<T, TValue>> property, TValue value)
{
var propertyName = property.GetPropertyName();
var propertySetter = typeof (T).GetProperty(propertyName).GetSetMethod(true);
propertySetter.Invoke(target, BindingFlags.NonPublic, null, new object[] {value}, null);
return value;
}
}
public static class ExpressionExtensions
{
public static string GetPropertyName<TModel, TProperty>(this Expression<Func<TModel, TProperty>> expression)
{
var body = expression.Body as MemberExpression;
return body.Member.Name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment