我在VS2010中使用MS单元测试。
我创建了一个读取文件的类。只是一个静态单词列表。该文件作为内容添加到主项目和测试项目中,并选择“始终复制”作为构建事件。
但是,当我运行单元测试时,它会在单元测试的输出目录中查找该文件。你如何让它看起来在bin目录中。我不想为了测试而混淆绝对文件路径...
Test method RequiredServicesTest.RequiredServices_JamesTest.Number2WordsTest threw exception:
Test method RequiredServicesTest.RequiredServices_JamesTest.Number2WordsTest threw exception:
System.IO.FileNotFoundException: Could not find file E:\scomA3proj\TestResults\James_JAMES-PC 2012-02-24 21_22_17\Out\randomdictionary.txt.
更新:我忘了提到的一件事是这是一个WCF服务库项目。
答案 0 :(得分:4)
请考虑以下技巧以获得正确的路径:
var assembly = typeof(RequiredServices_JamesTest).Assembly;
var assemblyPath = Path.GetDirectoryName(new Uri(assembly.EscapedCodeBase).LocalPath);
var filePath = Path.Combine(assemblyPath, "randomdictionary.txt");
// You have the correct file path now!
答案 1 :(得分:1)
您可以将单词列表文件作为部署项目,然后将其自动复制到测试输出目录中。
[TestClass()]
[DeploymentItem("randomdictionary.txt")]
public class SomeTestClass
{
//..
}
答案 2 :(得分:1)
我尝试将测试文件作为嵌入式资源存储在测试类中,并将它们解压缩到临时目录(具有自动清理/删除功能),因此我不必担心文件的存储位置。这种方式似乎更容易,更稳定。
答案 3 :(得分:0)
我决定使用这篇文章 https://msdn.microsoft.com/en-us/library/ms182475.aspx
保持简单的一个例子
我在dir TestData 中有测试数据(它在开发的这个阶段包含了对测试有用的所有目录和文件)。 内部 TestData 我有一个 TestCollisioni
指令路径: 的 UnitTestProject1 强> | - >的 TESTDATA 强> | - >的 TestCollisioni 强>
对于xcopy测试文件,我的命令onPostBuild事件(在上面的链接中有记录)是(如果需要,您只需要修改 UnitTstProject1 和 TestData 值)即仅当您使用不同的测试项目名称或不同的TestData目录名时))。
xcopy / Y / S" $(SolutionDir) UnitTestProject1 \ TestData *" " $(TARGETDIR)的 TESTDATA 强> \"
使用$(SolutionDir)和$(TargetDir)似乎是自动部署测试文件的最佳方法,不要改变它
测试方法具有DeploymentItem
的此值[TestMethod]
[DeploymentItem("TestData")]
在内部测试中,您可以访问测试数据内部的文件(以及该目录内的任何内容),例如:
Directory.Exists(@"的 TestCollisioni 强> \&#34),
所以我的工作测试测试是(NO" \"在 TestCollisioni 之前):
[TestMethod]
[DeploymentItem("**TestData**")]
public void TestMethod1()
{
Assert.IsTrue(Directory.Exists(@"TestCollisioni\"));
}