繁体   English   中英

在单元测试中读取 src 文件

[英]Read a src file in Unit test

我是 C# 和单元测试的新手。 我有一个配置文件存储在 Source 文件夹中(在服务器上)。 我需要在我的单元测试类中读取该文件。 这将在构建服务器上运行,因此需要找到一种解决方法。 类似 GetExecutingAssembly 的东西

  1. 将文件添加到同一个项目中,最好是在数据文件夹或类似的地方。

  2. 右键单击visual studio中的文件并选择属性,将操作设置为嵌入资源

  3. 根据您希望加载的防御程度,执行类似的操作

     using var stream = Assembly .GetAssembly(this.GetType()) .GetManifestResourceStream("<mynamspecase>.<myfilename>.<ext>"); Assert.NotNull(stream); var reader = new StreamReader(stream); string serialized = reader.ReadToEnd(); var dto = System.Text.Json.JsonSerializer.Deserialize<myfiletype>(serialized); Assert.NotNull(dto);

或者,如果不想将您的配置带到未知的测试服务器......但出于某种原因盲目地偏移您所在的位置,您可以使用您所在的位置作为导航点。

    string[] pathParts = 
    Assembly.GetAssembly(this.GetType()).Location.Split(@"\");
    //Go to party
    // now your text assembly is in last position, you will not be looking for that
    pathParts[pathParts.GetUpperBound(0)] = "";
    string basePathWhereWeExecute = string.Join(@"\", pathParts);
    var di = new DirectoryInfo(basePathWhereWeExecute);

    //You can combine, just jump up and down the path and use the following
    FileInfo[] whatFilesAreThere = di.GetFiles();            
    DirectoryInfo[] whatDirectoriesAreThere = di.GetDirectories();

    // I'd suspect you can get more info that just anywhere with a name if it's legit with somebody wanting you to succeed :D

您使用 NUnit、MSTest 或其他东西作为您的测试框架吗? 您可以使用 NUnit 的TestContext.TestDirectory或 MSTest 的TestContext.TestRunDirectory获取单元测试 dll 的目录。 然后我将配置文件添加到测试项目,并将其设置为复制到输出目录。 如果配置在您的存储库树中的其他位置,则可以将其作为链接文件添加到您的测试项目中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM