【发布时间】:2011-08-30 03:37:27
【问题描述】:
我有以下 IntegrationTest 项目结构...
如果我希望在NUnit Test 中使用该测试数据126.txt,如何加载该纯txt 文件数据?
注意:文件是 -linked-,我使用的是 c#(如图所示)。
干杯:)
【问题讨论】:
我有以下 IntegrationTest 项目结构...
如果我希望在NUnit Test 中使用该测试数据126.txt,如何加载该纯txt 文件数据?
注意:文件是 -linked-,我使用的是 c#(如图所示)。
干杯:)
【问题讨论】:
您可以在要复制到输出文件夹和单元测试内部的文件的属性中指定:
string text = File.ReadAllText(Path.Combine(TestContext.CurrentContext.TestDirectory, "TestData", "126.txt"));
作为替代方案,您可以将此文件作为资源嵌入到测试程序集中,然后:
var assembly = Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream("ProjectName.Tests.IntegrationTests.TestData.126.txt"))
using (var reader = new StreamReader(stream))
{
string text = reader.ReadToEnd();
}
【讨论】:
Build Action 设置为EmbeddedResource,而不仅仅是Resource。我很困惑,因为WPF 以其他方式对待它:link
如果您不希望文件作为 ManifestResources,而只是作为系统上的文件。请参阅Trouble with NUnit when determining the assembly's directory 了解更多信息,尤其是this answer
同样有趣的是来自 NUnit https://bugs.launchpad.net/nunit-vs-adapter/+bug/1084284/comments/3的信息
但这里是快速信息:
Path.Combine(TestContext.CurrentContext.TestDirectory, @"Files\test.pdf")
Files\test.PDF 只是测试项目中的一个文件,包含构建操作内容并复制到输出目录副本(如果更新)
所有学分都归其他帖子中的人所有,但我花了一段时间才找到答案,这就是我在这篇帖子中添加答案的原因。
【讨论】:
这个问题目前已得到解答,但对于寻找其他可能性的谷歌用户来说:
如果您因为测试在C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common... 而不是bin\Debug\... 中查找而得到DirectoryNotFoundException,这意味着您的测试适配器正在从不是您的测试项目输出目录的路径执行。
要解决这个问题,您可以通过查找测试 DLL 的目录来获得 bin\Debug\... 目录,如下所示:
using System.IO;
using System.Reflection;
// Get directory of test DLL
var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
// dir is now "C:\...\bin\Debug" or wherever the executable is running from
我将它放在测试项目的TestHelpers 静态类中,这样我就可以在需要加载外部文件的每个测试中使用它。
代码由this answer提供。
【讨论】:
使用TestContext.CurrentContext.TestDirectory 发现了一个问题。这在设置中完美运行,但是当我从提供给 TestCaseSource 的方法中调用它时,静态方法在所有其他代码之前调用,并返回以下内容:
C:\Users\<username>\.nuget\packages\nunit\3.10.1\lib\netstandard2.0
但是,使用 TestContext.CurrentContext.WorkDirectory 在两个地方都可以得到所需的结果:
C:\SVN\MyApp\trunk\MyApp.Tests\bin\Debug\netcoreapp2.1
【讨论】: