![](/img/trans.png)
[英]How can I retrieve data from an external XML file and place it in an HTML file?
[英]How can I use an Excel file as test data correctly?
如何最好地使用 Excel 文件作为 xUnit 测试的输入? 请注意,我不想使用 Excel 内部的数据,而是 Excel 本身。
假设我有一个 UnitTests 项目,我想在其中放置一些 Excel 文件,我需要将其放入我的测试中:
[Fact]
public void Constructor_ShouldReadExcelFile()
{
var mapping = new ExcelMapping("excelfiles/test1.xlsx");
Assert.True(mapping.Valid);
}
但是,当运行它时, CurrentWorkingDirectory
被设置为bin\Debug.net7.0
目录,我需要创建一个相对路径:
[Fact]
public void Constructor_ShouldReadExcelFile()
{
var mapping = new ExcelMapping("../../../excelfiles/test1.xlsx");
Assert.True(mapping.Valid);
}
这会奏效,但这是“正确”的方式吗?
你的解决方案对我来说很好。
我经常需要检索单元测试的测试数据文件,一般是这样进行的。 测试数据也受版本控制,但与单元测试位于不同的文件夹中。 在我的单元测试 class 中,我为测试数据定义了一个相对路径,并为绝对路径创建了一个成员:
const string testDataRelativePath = @"..\..\..\..\excelfiles\";
string testDataFolderAbsolutePath;
相对路径是相对于单元测试dll所在项目文件夹为output。
在测试 class 的构造函数中,我为绝对路径定义了一个值。
using System.IO;
using System.Reflection;
public class MyTestClass
{
public MyTestClass()
{
string projectDir = getProjectDir();
testDataFolderAbsolutePath = Path.GetFullPath(Path.Combine(projectDir, testDataRelativePath));
}
internal static string getProjectDir()
{
Assembly assembly = Assembly.GetExecutingAssembly();
return directoryPathNameFromAssemblyCodeBase(assembly);
}
internal static string directoryPathNameFromAssemblyCodeBase(Assembly assembly)
{
Uri codeBaseUrl = new Uri(assembly.CodeBase);
string codeBasePath = Uri.UnescapeDataString(codeBaseUrl.AbsolutePath);
return Path.GetDirectoryName(codeBasePath);
}
// ... Tests ...
}
在测试本身中,我会做这样的事情:
string excelFilePath = Path.Combine(testDataFolderAbsolutePath, "test1.xlsx");
我发现这在运行测试的多个系统上给出了更好的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.