Question

I'm creating an object serialization unit test and want to inline the XML of the object inside the c# code unit test file. I know the easiest way to inline it is to use the @ prefix as a string:

var xml = @"<Something> 
                 <AnotherSomething/>
                 <AnotherSomething/>
            </Something>";

my problem is that my XML contains attributes and it is very big, and in order to inline it I will need to go over all the XML and put escape for each """ in the XML, doing that for a very big XML node is hard and maintaining it would be hard -

var xml = @"<Something Att=""s"" Att2=""gg""> 
                     <AnotherSomething/>
                     <AnotherSomething/>
           </Something>";

I don't want to put the XML as another file and mark it as deployment Item -

[DeploymentItem("Something.xml")]

Since it will require the unit test to load the file from disk which will make the unit test much slower and I might have many of those.

Is there any other way to put the XML inside the code without modifications?

Was it helpful?

Solution

As @leon's comment suggests use a resource file, but I go further.

  1. Add a folder Resources
  2. Add a Resources.resx file (rename as required)
  3. Add your xml file with test data TestData.xml
  4. Make it embedded resource
  5. Drag the xml file from the solution explorer to the Resource.resx
  6. Make sure your TestData.xml resource type is text and not binary
  7. Compile

Now refer to your test data as

string data = Resources.TestData;

OTHER TIPS

Instead of xml string, you can create xml representation using linq to xml objects. The second example would look like that:

var xml = 
    new XElement("Something",
        new XAttribute("Att", "s"),
        new XAttribute("Att2", "gg"),
        new XElement("AnotherSomething"),
        new XElement("AnotherSomething"));

More reasons to use this, are assuring xml validity, auto escaping special characters, more formatting options when converting to string, and - much easier to work on.

No, the compiler/parser wont allow it.

You could put all your xml in a single file (in some sort of valid structure) and have a utility class load the entire thing and cache it between tests.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top