Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I include sample data files in VS unit tests?

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.

like image 326
Firoso Avatar asked Mar 21 '11 21:03

Firoso


Video Answer


1 Answers

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

like image 120
bryanbcook Avatar answered Oct 01 '22 07:10

bryanbcook