i am trying to test this method:
[Test]
public void Test_GetReferenceValue()
{
Person person= new Person() { Name = "PJ" };
PersonalProperty<Person> personalProperty = new PersonalProperty<Person>();
var result = personalProperty.GetReferenceValue(person);
Assert.AreEqual("PJ", result);
}
the method GetReferenceValue has the following implementation:
public override object GetReferenceValue(TOwner owner)
{
Person value = this.Accessor(owner);
if (value == null)
return null;
else
return value.Name;
}
i tried to find the origin of the Accessor property, and i found it in ANOTHER assembly:
public class PersonalProperty<TOwner> : Property<TOwner, Person>
where TOwner : class
{
public virtual Func<TOwner, TProperty> Accessor { get; internal set; }
}
my test above will run perfectly if only i can put the code in my test:
personalProperty.Accessor = p =>p;
this is to put a definition/method for the Func delegate.. however, i cant do this because Accessor is internally set. Meaning, i cant set it if i am in an another assembly (which i am right now). i cant friend the Accessor's assembly because i am not allowed to change any code. i am only allowed to create a test in an another project/assembly.
so how am i going to test GetReferenceValue? can reflection help?
Yes, you can do it using reflection. This function can set property value ignoring setter access modifier:
public static void SetPropertyValue(object instance, string property, object value)
{
instance.GetType().GetProperty(property).SetValue(instance, value, null);
}
Usage:
Func<Person, Person> accessor = p => p;
SetPropertyValue(personalProperty, "Accessor", accessor);
Anyway, it is an indicator that something might be wrong with PersonalProperty<T>
class design.