Using Reflection to set the private field on a passed class

Tags: C#, Unit Testing

In unit testing I often want to check a private field has been set when running a test and I created the following helper method to do that:

   1: /// <summary>
   2: /// Set private field on passed instance (includes readonly fields)
   3: /// </summary>
   4: /// <typeparam name="TInstance">Type of instance</typeparam>
   5: /// <typeparam name="TField">Type of field</typeparam>
   6: /// <param name="instance">Instance to set private field on</param>
   7: /// <param name="fieldName">Field name</param>
   8: /// <param name="fieldValue">Value to set on field</param>
   9: public static void SetPrivateField<TInstance, TField>(TInstance instance, string fieldName, TField fieldValue)
  10: {
  11:     var fieldInfo =
  12:         instance.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Where(
  13:             f => f.Name == fieldName).FirstOrDefault();
  14:  
  15:     if (fieldInfo == null)
  16:     {
  17:         throw new InvalidOperationException(string.Format(
  18:             "Cannot find field named '{0}' on type '{1}'.", fieldName, typeof(TInstance)));
  19:     }
  20:  
  21:     if (fieldInfo.FieldType.Name != typeof(TField).Name)
  22:     {
  23:         throw new InvalidOperationException(string.Format(
  24:             "Field named '{0}' has a different type '{1}' from the one expected '{2}'",
  25:             fieldName,
  26:             fieldInfo.FieldType.Name,
  27:             typeof(TField).Name));
  28:     }
  29:  
  30:     fieldInfo.SetValue(instance, fieldValue);
  31: }

As you can see it just uses reflection to get at the private field on the passed instance.

Add a Comment