visual-studio 单元测试:如何访问文本文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1805012/
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-10-22 11:15:42  来源:igfitidea点击:

Unit testing: how to access a text file?

visual-studiovisual-studio-2008unit-testing

提问by Pablote

I'm using Visual Studio 2008 with Microsoft test tools. I need to access a text file from within the unit test.

我将 Visual Studio 2008 与 Microsoft 测试工具一起使用。我需要从单元测试中访问一个文本文件。

I've already configured the file with build action set to 'Content' and copy to output directory to 'Copy Always', but the file is not being copied to the output directory, which according to System.Environment.CurrentDirectoryis

我已经配置了生成操作设置为“内容”的文件,并复制到输出目录“一直拷贝”,但该文件没有被复制到其中根据输出目录,System.Environment.CurrentDirectory就是

'{project_path}\TestResults\Pablo_COMPU 2009-11-26 15_01_23\Out'

'{project_path}\TestResults\Pablo_COMPU 2009-11-26 15_01_23\Out'

This folder contains all the DLL dependencies of the project, but my text file is not there.

该文件夹包含项目的所有 DLL 依赖项,但我的文本文件不存在。

Which is the correct way to access a text file from a unit test?

从单元测试访问文本文件的正确方法是什么?

回答by Alexander Egger

You have to add the DeploymentItemattribute to your test class. With this attribute you specify the files which are copied into the out directory for the test run.

您必须将该DeploymentItem属性添加到您的测试类中。使用此属性,您可以指定复制到测试运行的 out 目录中的文件。

For example:

例如:

[TestMethod]
[DeploymentItem(@"myfile.txt", "optionalOutFolder")]
public void MyTest()
{
    ...
}

See also: http://msdn.microsoft.com/en-us/library/ms182475.aspx.

另请参阅:http: //msdn.microsoft.com/en-us/library/ms182475.aspx

回答by Gavin

Alternatively if you set all your text files to "Copy to build directory" then you could reference their path in your tests by doing this

或者,如果您将所有文本文件设置为“复制到构建目录”,那么您可以通过执行此操作在测试中引用它们的路径

var directory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
var path = string.Format("{0}\{1}",directory,"myFile.txt");

回答by Mark Simpson

I can't answer your question as I don't use MSTest. However, I'd consider whether accessing the file system in a unit test is the right thing to do. If you introduce a dependency on the file system, the test will become slower and less trustworthy (you now depend on something that may not be there/accessible/etc). It is for these reasons that many folk will say "it's not a unit test if it hits the file system".

我无法回答您的问题,因为我不使用 MSTest。但是,我会考虑在单元测试中访问文件系统是否正确。如果您引入了对文件系统的依赖,测试将变得更慢且更不可信(您现在依赖于可能不存在/可访问/等的东西)。正是由于这些原因,许多人会说“如果它击中文件系统,这不是单元测试”。

Although this is not a hard rule, it's always worth considering. Any time I have to touch the file system in tests, I try to avoid it because I find tests that rely on files are harder to maintain and are generally less consistent.

尽管这不是硬性规定,但始终值得考虑。任何时候我必须在测试中接触文件系统时,我都会尽量避免它,因为我发现依赖于文件的测试更难维护并且通常不太一致。

I'd consider abstracting the file operationsto some degree. You can do numerous things here, from changing the internal loading strategy (via Dependency Injection) to -- even better -- separating the loading/use of the file so that the consumer of the file's contents doesn't even have to careabout the loading strategy.

我会考虑某种程度上抽象文件操作。你可以在这里做很多事情,从改变内部加载策略(通过依赖注入)来-甚至更好-分装/使用的文件,这样的文件的内容,消费者甚至不必去关心有关加载策略。

回答by Don Kirkby

When I need a chunk of text as part of a unit test and it's more than a line or two, I use an embedded resource. It doesn't clutter your test code, because it's a separate text file in the source code. It gets compiled right into the assembly, so you don't have to worry about copying around a separate file after compilation. Your object under test can accept a TextReader, and you pass in the StreamReader that you get from loading the embedded resource.

当我需要一段文本作为单元测试的一部分并且超过一两行时,我会使用嵌入式资源。它不会使您的测试代码混乱,因为它是源代码中的一个单独的文本文件。它被直接编译到程序集中,因此您不必担心在编译后复制单独的文件。被测对象可以接受 TextReader,并传入从加载嵌入资源中获得的 StreamReader。

回答by vicsz

How are you running your tests?

你如何运行你的测试?

We use (TestDriven.net -> Run Tests).

我们使用(TestDriven.net -> 运行测试)。

From my experience, some test runners (like Junit in Netbeans) won't automatically copy any additional text files that you might need for testing. So in your case you might have to do a full build, and then try running the tests again.

根据我的经验,一些测试运行器(如 Netbeans 中的 Junit)不会自动复制您可能需要的任何其他测试文本文件。因此,在您的情况下,您可能必须进行完整构建,然后再次尝试运行测试。

And the correct way for accessing text files from tests is the way you're trying to do it. (Setting the files to "copy always" and "content", and accessing them from the compiled directory).

从测试中访问文本文件的正确方式就是您尝试这样做的方式。(将文件设置为“始终复制”和“内容”,并从编译目录访问它们)。

Also, not sure where people are getting the idea that having tests rely on files is a bad thing. It's not.

此外,不确定人们从哪里得到的想法依赖于文件是一件坏事。不是。

If anything, having separate test files, will only clean up your tests and make them more readable. Consider some xml parsing method that returns a large string:

如果有的话,拥有单独的测试文件只会清理您的测试并使它们更具可读性。考虑一些返回大字符串的 xml 解析方法:

String expectedOutput = fileOperator.ReadStringFromFile("expectedFileContents.xml");
String result = systemUnderTest.Parse(somethingtoparse);
Assert.Equals(expectedOutput, result);

Imagine if the output was 30 lines long, would you clutter your test code with one giant String? or just read it from a file.

想象一下,如果输出有 30 行长,你会用一个巨大的 String 把你的测试代码弄得一团糟吗?或者只是从文件中读取它。