如何在 VS 单元测试中包含示例数据文件? [英] How can I include sample data files in VS unit tests?

查看:25
本文介绍了如何在 VS 单元测试中包含示例数据文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想针对示例 XML 文件运行单元测试.我应该如何将这些文件暴露给单元测试?我已尝试使用内容构建操作,但我无权访问应用程序上下文,因此 GetContentStream 已失效.

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.

我知道我可以将 DataContext 用于 SQL 数据库,但我觉得这是错误的方法.

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

推荐答案

如果您希望在测试中部署 XML 文件,您有几个选择:

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

嵌入内容

您可以将 Xml 文件作为内容嵌入到程序集中.

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

  1. 将文件添加到您的测试项目中.在本示例的上下文中,该文件位于项目的根目录下.
  2. 将文件的属性更改为嵌入式资源.
  3. 在测试期间,您可以使用 获取清单资源.

示例:

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

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

    Assert.IsNotNull( xmlDoc.InnerXml );
}

DeploymentItemAttribute

您可以使用 [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);
}

测试设置

您可以使用测试设置文件中的部署配置来部署单个文件或整个目录.(测试 -> 编辑设置 -> 文件名.testsettings)

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

这篇关于如何在 VS 单元测试中包含示例数据文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆