My project has separate unit tests in which we want to set some properties that have private setters. I am currently doing this through reflection and this extension method:
public static void SetPrivateProperty(this object sourceObject, string propertyName, object propertyValue) { sourceObject.GetType().GetProperty(propertyName).SetValue(sourceObject, propertyValue, null); }
Assuming I have a TestObject like this:
public class TestObject { public int TestProperty{ get; private set; } }
Then I can call it in my unit tests as follows:
myTestObject.SetPrivateProperty("TestProperty", 1);
However, I would like to have the property name validation at compile time, and therefore I would like to pass the property in the expression through the expression, for example:
myTestObject.SetPrivateProperty(o => o.TestProperty, 1);
How can i do this?
Sterno
source share