Created
April 15, 2010 15:29
-
-
Save gshutler/367226 to your computer and use it in GitHub Desktop.
Extension method for setting non-public properties in tests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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