2

Say I have a method that takes a list of objects. The method will normally take 20 objects easy. Each object has 15 or so properties on them.

To unit test this, I need to type out all 20 objects so that I can pass them into my method.

This is frustrating when I can see perfectly good examples of what I need sitting there in my debugger watch window.

Is there a tool to take an object that I have and make it output to C#?

NOTE: I saw this question: How can I serialize an object to C# object initializer code? but the code it generates does not work...

I can't think I am the first to want this. Is it harder than I think? or are there tools out there that do it already?

Community
  • 1
  • 1
Vaccano
  • 78,325
  • 149
  • 468
  • 850

2 Answers2

3

I created a visual studio plugin called Object Exporter which does exactly this. You can export an object instance in C#, JSON or XML.

Omar Elabd
  • 1,914
  • 1
  • 18
  • 23
1

I often use the JavaScriptSerializer Class to convert extensive objects to/from text for unit testing purposes:

var fruits = new List<string>();
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Blueberry");
fruits.Add("Orange");

var jss = new JavaScriptSerializer();
var text = jss.Serialize(fruits);
Console.WriteLine(text);

The code above will produce the following output:

["Apple","Banana","Blueberry","Orange"]

Which can be converted back to an object like shown below:

var jss = new JavaScriptSerializer();
var text = "[\"Apple\",\"Banana\",\"Blueberry\",\"Orange\"]";
var fruits = jss.Deserialize<List<string>>(text);

This workaround has saved me from a lot of boring typing ;)

Thomas C. G. de Vilhena
  • 13,819
  • 3
  • 50
  • 44