C# Visual Studio - 单元测试加载项目中的资源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1541096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:38:37  来源:igfitidea点击:

Visual Studio - Unit tests loading resources in the project

c#visual-studiounit-testingfilepath

提问by p.campbell

The goal is to run some tests given some data in those Xml files.

目标是在给定这些 Xml 文件中的一些数据的情况下运行一些测试。

How would you easily load a given Xml file into an XmlDoc within the unit test methods?

您如何在单元测试方法中轻松地将给定的 Xml 文件加载到 XmlDoc 中?

Current state is:

目前的状态是:

  XmlDocument doc = new XmlDocument();
  string xmlFile = "4.xml";
  string dir = System.IO.Directory.GetCurrentDirectory() + @"\Msgs\" 

  //dir is then the value of the current exe's path, which is
  //d:\sourcecode\myproject\TestResults\myComputer 2009-10-08 16_07_45\Out

  //we actually need:
  //d:\sourcecode\myproject\Msgs\ 
  doc.Load( dir + fileName); //should really use System.IO.Path.Combine()!

Is it just a simple matter of putting that path in an app.config? I was hoping to avoid that, given the possibilityof different paths on developer machines.

将这条路径放入一个简单的问题app.config吗?鉴于开发人员机器上可能存在不同的路径,我希望避免这种情况。

Question:How would you write the algorithm to load a given Xml file into an XmlDocument in the unit test method?

问题:在单元测试方法中,您将如何编写将给定 Xml 文件加载到 XmlDocument 中的算法?

采纳答案by HitLikeAHammer

In the unit test project add a post-build event that copies the XML file to the output directory. Then, you can use your original code to get the XML file.

在单元测试项目中添加一个将 XML 文件复制到输出目录的构建后事件。然后,您可以使用原始代码来获取 XML 文件。

The post build event will look like something like this:

构建后事件将如下所示:

copy $(SolutionDir)file.xml $(ProjectDir)$(OutDir)file.xml

You may also need this to add to your path:

您可能还需要将其添加到您的路径中:

Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

回答by Andrew Keith

I would just put the path in the app.config and load from the default path. In my team, i am really anal about developers changing paths, so i make all my developers have the same exact paths and files on their computers, so i dont have an issue of any rogue developer changing a path to suite his workspace.

我只是将路径放在 app.config 中并从默认路径加载。在我的团队中,我真的很讨厌开发人员更改路径,所以我让我所有的开发人员在他们的计算机上拥有完全相同的路径和文件,所以我没有任何流氓开发人员更改路径以适应他的工作区的问题。

For example , all developers in my team must use C:\Project\Product\Module, etc etc. I also make sure all their software installed also is standard. This way, i can ghost any machine into any other easily.

例如,我团队中的所有开发人员都必须使用 C:\Project\Product\Module 等。我还确保他们安装的所有软件也是标准的。这样,我可以轻松地将任何机器幻影到任何其他机器上。

回答by ChrisW

You can build those files into your executable (set their "Build Action" property to "Embedded Resource") and then get them using the Assembly.GetManifestResourceStream method.

您可以将这些文件构建到您的可执行文件中(将它们的“构建操作”属性设置为“嵌入式资源”),然后使用Assembly.GetManifestResourceStream method.

回答by Chris Moschini

I use a helper class to deal with getting basic paths I might want to access in my Unit Tests.

我使用一个辅助类来处理获取我可能想要在我的单元测试中访问的基本路径。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Brass9.Testing
{
    public static class TestHelper
    {
        public static string GetBinPath()
        {
            return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        }

        public static string GetProjectPath()
        {
            string appRoot = GetBinPath();
            var dir = new DirectoryInfo(appRoot).Parent.Parent.Parent;
            var name = dir.Name;
            return dir.FullName + @"\" + name + @"\";
        }

        public static string GetTestProjectPath()
        {
            string appRoot = GetBinPath();
            var dir = new DirectoryInfo(appRoot).Parent.Parent;
            return dir.FullName + @"\";
        }

        public static string GetMainProjectPath()
        {
            string testProjectPath = GetTestProjectPath();
            // Just hope it ends in the standard .Tests, lop it off, done.
            string path = testProjectPath.Substring(0, testProjectPath.Length - 7) + @"\";
            return path;
        }
    }
}

Sometimes my interactions with paths are more complex; I often use a central class I name "App" to indicate some basic details about the application, like its root folder, its root namespace and module, etc. Classes will sometimes depend on App's existence, and so instead I'll place an init method on App that uses code like the above to initialize itself for test harnesses, and call that method from the Init command in a Unit Test.

有时我与路径的交互更复杂;我经常使用一个我命名为“App”的中心类来表示应用程序的一些基本细节,比如它的根文件夹、它的根命名空间和模块等。类有时会依赖于 App 的存在,因此我将放置一个 init App 上的方法使用上述代码为测试工具初始化自身,并从单元测试中的 Init 命令调用该方法。

(Updated)

(更新)

Old Answer

旧答案

I found this helps for getting arbitrary paths to access files in the project folder you intend to test (as opposed to files in the Test project folder, which can make busywork if you need to copy things over).

我发现这有助于获取任意路径来访问您打算测试的项目文件夹中的文件(而不是 Test 项目文件夹中的文件,如果您需要复制内容,这会使工作变得繁忙)。

DirectoryInfo projectDir = new DirectoryInfo(@"..\..\..\ProjectName");
string projectDirPath = projectDir.FullName;

You can then use either of those variables to access whatever you need from the related project. Obviously swap "ProjectName" out for the actual name of your project.

然后,您可以使用这些变量中的任何一个来访问相关项目中您需要的任何内容。显然,将“ProjectName”换成项目的实际名称。

回答by Pieter Müller

There is a Visual Studio Unit Testing feature for this: DeploymentItemAttribute

为此有一个 Visual Studio 单元测试功能:DeploymentItemAttribute

I use this feature to copy all xml files in a given project folder to the unit test output folder, before testing if all required files are present.

在测试是否存在所有必需文件之前,我使用此功能将给定项目文件夹中的所有 xml 文件复制到单元测试输出文件夹。

You can use this attribute with your unit tests to copy specific files from the Project folder (or anywhere else) to the Unit Test output folder. Like so:

您可以在单元测试中使用此属性,将特定文件从项目文件夹(或其他任何地方)复制到单元测试输出文件夹。像这样:

[TestMethod()]
[DeploymentItem("MyProjectFolder\SomeDataFolder\somefile.txt", "SomeOutputSubdirectory")]
public void FindResourcefile_Test()
{
    string fileName = "SomeOutputSubdirectory\somefile.txt";
    Assert.IsTrue(System.IO.File.Exists(fileName));
}

You can also copy the contents of whole folders:

您还可以复制整个文件夹的内容:

[TestMethod()]
[DeploymentItem("MyProjectFolder\SomeDataFolder\", "SomeOutputSubdirectory")]
public void FindResourcefile_Test()
{
    string fileName = "SomeOutputSubdirectory\someOtherFile.txt";
    Assert.IsTrue(System.IO.File.Exists(fileName));
}

The first parameter is the source, the second the destination folder. The source is relative to your solution folder (so you can access the Unit Test project of the project being tested) and the destination is relative to the output folder of the unit test assembly.

第一个参数是源,第二个参数是目标文件夹。源相对于您的解决方案文件夹(因此您可以访问被测试项目的单元测试项目),目标相对于单元测试程序集的输出文件夹。

UPDATE:

更新:

You need to enable Deployment in the Test Settings for this to work. This MSDN page explains how (it's real easy): http://msdn.microsoft.com/en-us/library/ms182475(v=vs.90).aspx#EnableDisableDeploy

您需要在测试设置中启用部署才能使其工作。这个 MSDN 页面解释了如何(这真的很简单):http: //msdn.microsoft.com/en-us/library/ms182475(v=vs.90) .aspx#EnableDisableDeploy

回答by freeze

I think in VS.NET 2012 DeploymentItem attribute works without any Test Settings configuration.

我认为在 VS.NET 2012 DeploymentItem 属性中没有任何测试设置配置。

回答by vezenkov

Resources are just resources and that's it, no need to complicate. If you don't want to embed them then you could add these files as "Content" resources to your project and set them to Copy always. Then specify the sub-folder in your code:

资源就是资源,仅此而已,无需复杂化。如果您不想嵌入它们,那么您可以将这些文件作为“内容”资源添加到您的项目中,并将它们设置为Copy always. 然后在代码中指定子文件夹:

var xmlDoc = XElement.Load("ProjectSubFolder\Resource.xml");

This will automatically load the resources from the project output (running assembly location) bin\$(Configuration)\ResourceSubfolder\

这将自动从项目输出(运行程序集位置)加载资源 bin\$(Configuration)\ResourceSubfolder\

This works for all types of projects, not just unit tests.

这适用于所有类型的项目,而不仅仅是单元测试。