【问题标题】:How can I use an Excel file as test data correctly?如何正确使用Excel文件作为测试数据?
【发布时间】:2023-02-02 00:49:00
【问题描述】:

如何最好地使用 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);
}

这会奏效,但这是“正确”的方式吗?

【问题讨论】:

    标签: external xunit


    【解决方案1】:

    你的解决方案对我来说很好。

    我经常需要检索单元测试的测试数据文件,一般是这样进行的。测试数据也受版本控制,但与单元测试位于不同的文件夹中。在我的单元测试类中,我为测试数据定义了一个相对路径,并为绝对路径创建了一个成员:

            const string testDataRelativePath = @"........excelfiles";
            string testDataFolderAbsolutePath;
    

    相对路径是相对于输出单元测试dll的项目文件夹。

    在测试类的构造函数中,我为绝对路径定义了一个值。

    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");
    

    我发现这在运行测试的多个系统上给出了更好的结果。

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2019-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多