【发布时间】:2022-01-10 14:08:51
【问题描述】:
我对 C# 相当生疏。我一直在互联网上寻找解决方案,但没有成功。
我使用 MSTest 创建了一个测试项目。一些测试使用文件,这些文件是我添加到 TestData 文件夹下的项目测试中的,它们在执行测试时使用属性 DeploymentItem 进行复制。
示例:[DeploymentItem(@"TestData\test.txt")]
这会在执行文件夹中复制 test.txt 并且可以正常工作。但是,当我想在测试中使用这个文件时,我必须使用“test.txt”而不是@“TestData\test.txt”。因此,如果我想分解我的代码,我必须有两个变量:
const string testFileName = "test.txt";
const string testFilePath = @"TestData\test.txt";
然后将它们用作
[DeploymentItem(testFilePath)]
public void TestFunction()
{
[...]testFileName[...]
}
理想情况下,我想改为:
[DeploymentItem(testFilePath)]
public void TestFunction()
{
[...]testFilePath[...]
}
这样我只需要一个变量。
如果我这样使用 DeploymentItem 的第二个参数,它会起作用:
const string testFilesFolder = "TestData";
const string testFilePath = @"TestData\test.txt";
[DeploymentItem(testFilePath, testFilesFolder)]
public void TestFunction()
{
[...]testFilePath[...]
}
但是,这迫使我和每个人每次使用 DeploymentItem 时都要考虑传递第二个参数。但它有工作的优点。
为了解决这个问题,我尝试了以下不同的方法:
- 从 DeploymentItem 继承来简单地添加我自己的构造函数:DeploymentItem 是密封的,所以这是不可能的。
- 通过复制 DeploymentItem 的代码来创建我自己的属性。该文件根本没有被复制:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
class DeployFileAttribute : Attribute
{
public DeployFileAttribute(string path)
{
Path = path;
OutputDirectory = System.IO.Path.GetDirectoryName(path);
}
public string Path { get; }
public string OutputDirectory { get; }
}
[DeployFile(testFilePath)] // testFilePath is not copied at all, even though the constructor is correctly executed.
- 创建将返回属性的方法。似乎不可能将方法的结果用作属性:
public static DeploymentItemAttribute DeployFile(string path)
{
return new DeploymentItemAttribute(path, System.IO.Path.GetDirectoryName(path));
} // No compilation error
[DeployFile(testFilePath)] // DeployFileAttribute type does not exist
- 使用语句或 C 样式宏创建类似 C++ 样式的东西,我似乎找不到有效的语法
using DeployFile(string toto) = DeploymentItemAttribute(toto, System.IO.Path.GetDirectoryName(path)); // Syntax is wrong, could not find one that works
欢迎任何后见之明!
【问题讨论】: