Search code examples
visual-studioresharpervisual-studio-debugging

Visual Studio: capture object state in debug mode and use it in unit test


Is there an easy and elegant way to capture objects in debug mode and just dump them in the unit tests? I am using some very large object (like 30+ fields) and i would need that as data in my unit tests.


Solution

  • I don't know of any quick-and-easy way of doing this and, in fact, I suspect that the whole issue with field/properties, nesting, private-public prevents VS from providing a general-purpose solution for this.

    You could certainly use serialization, for example calling some {{MyHelper.ToInitExpression()}} in the Immediate window while debugging and then taking the clipboard data and putting it into your unit tests. To make the initialization expression you would need to use reflection to find out what properties/fields there are and what their current values are. If you have nested objects, you'll need to take care of those too.

    An alternative, if you go the ReSharper route, is to generate some sort of ToInit() method. You would need to make these individually for each of the classes you need. This is rather easy using ReSharper's generator infrastructure. Feel free to ping me (skype:dmitri.nesteruk) if you need help with this.

    The other alternative is to simply hand-craft such methods, for example:

    public static string ToAssemblyCode(this DateTime self)
    {
      var sb = new StringBuilder("new System.DateTime(");
      sb.AppendFormat("{0},{1},{2}", self.Year, self.Month, self.Day);
      if (self.Hour != 0 || self.Minute != 0 || self.Second != 0)
        sb.AppendFormat(",{0},{1},{2}", self.Hour, self.Minute, self.Second);
      if (self.Millisecond != 0)
        sb.AppendFormat(",{0}", self.Millisecond);
      sb.Append(")");
      return sb.ToString();
    }