17

I've got unit tests I want to run against a sample XML file. How should I go about exposing these files to the unit tests? I've tried playing with the content build action, but I don't have access to an application context so GetContentStream is out.

I'm aware I can use a DataContext to a SQL Database, but I feel this is the wrong approach.

Pang
  • 9,564
  • 146
  • 81
  • 122
Firoso
  • 6,647
  • 10
  • 45
  • 91

1 Answers1

21

If you are looking to deploy the XML file with your tests, you have a few options:

Embedded Content

You can embed the Xml file as content within the assembly.

  1. Add the file to your test project. In the context of this example, the file is located at the root of the project.
  2. Change the properties of the file to be an Embedded Resource.
  3. During the test you can get access to the file as a stream by using the get manifest resource.

Example:

[TestMethod]
public void GetTheFileFromTheAssembly()
{
    Stream fileStream = Assembly.GetExecutingAssembly()
                          .GetManifestResourceStream("MyNamespace.File.xml");

    var xmlDoc = new XmlDocument();
    xmlDoc.Load(fileStream);

    Assert.IsNotNull( xmlDoc.InnerXml );
}

DeploymentItemAttribute

You can annotate the test method or class with a [DeploymentItemAttribute]. The file path is relative to the solution.

[DeploymentItem("file.xml")] // file is at the root of the solution
[TestMethod]
public void GetTheFileDeployedWithTheTest()
{
    var xmlDoc = new XmlDocument();
    xmlDoc.Load("file.xml");

    Assert.IsNotNull(xmlDoc.InnerXml);
}

Test Settings

You can deploy individual files or entire directories using the Deployment configuration inside the Test Settings file. (Tests -> Edit Settings -> Filename.testsettings)

enter image description here

Pang
  • 9,564
  • 146
  • 81
  • 122
bryanbcook
  • 16,210
  • 2
  • 40
  • 69
  • 1
    Just wanted to point out the importance of the "*MyNamespace*.File.xml" in the embedded resource example. I totally glossed over that the namespace was necessary there when trying this out. – Jordan T. Cox Oct 23 '13 at 05:47
  • 1
    If your test fails while using the `[DeploymentItemAttribute]` option and a test warning **Deployment is currently disabled. ...** appears in the details, make sure you've **enabled Deployment** in the **.testsettings** file. Only this in addition, because I actually ran into it. If you want to know more about configuring test deployment, [follow this link](http://msdn.microsoft.com/en-us/library/ms182475(v=vs.100).aspx). – Christian St. Nov 11 '13 at 16:17
  • 1
    FYI, the first solution requires `using System.Reflection`. – Godsmith Dec 03 '14 at 09:33
  • Just noting that the `DeplyomentItem` can be on the class as well as methods. – cjb110 Mar 16 '23 at 11:42