Last active
November 7, 2018 16:05
-
-
Save mattfrear/b555286dd5767cea632c003111ec0334 to your computer and use it in GitHub Desktop.
With method for setting any property on any object including read only properties (for tests)
This file contains 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 ObjectExtensions | |
{ | |
public static T With<T, TProp>(this T o, Expression<Func<T, TProp>> prop, TProp value) | |
{ | |
if (!(prop.Body is MemberExpression memberExpression)) | |
{ | |
throw new ArgumentException($"A property must be provided. ({prop})"); | |
} | |
var propertyInfo = (PropertyInfo) memberExpression.Member; | |
if (propertyInfo.CanWrite) | |
{ | |
propertyInfo.SetValue(o, value); | |
} | |
else | |
{ | |
typeof(T).GetField($"<{propertyInfo.Name}>k__BackingField", | |
BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(o, value); | |
} | |
return o; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage:
then in your test:
This saves you from inventing dummy data for all the constructor parameters which you don't care about.