如何设置C#测试单元测试的工作目录



我在Linux下使用VS代码(Debian Buster(,目前使用MSTest框架编写一些单元测试。我的一些测试必须读取我存储在测试项目NewAppTest中的文件。UnitTest1.cs需要读取some_data.json,目录结构:

NewAppTest
+ UnitTest1.cs
+ some_data.json

在UnitTest1.cs中,我使用此代码读取some_data.json:

[TestMethod]    
public void GetEmployee()
{
var data = File.ReadAllText("../../../some_data.json");
Assert.IsNotNull(data);
}

我需要在文件名前面加上"../../..",这让我很恼火/&";。肯定有更好的方法来设置当前的工作目录。我在谷歌上搜索了一些,找到了这个和这个,但我不明白。

我想创建一个类似于.runsettings的文件,在其中我为项目中的所有测试指定当前工作目录。我宁愿不必碰每一个测试班。

一个适合我的用例的最小运行设置示例会很好。

在测试应用程序中包含文件的一个好方法是使用嵌入式资源。嵌入式资源与测试构建捆绑在一起,因此它们与测试构建的位置无关。要嵌入文件,请编辑.csproj文件并添加以下项目组(作为<Project>的子项(:

<ItemGroup>
<EmbeddedResource Include="some_data.json" />
</ItemGroup>

(如果some_data.json位于项目中的子文件夹中,则路径为subfolder/some_data.json(。

要读取嵌入式资源,请使用GetManifestResourceStream:

var assembly = typeof(UnitTest1).Assembly; //Get the assembly in which the resources are embedded
using Stream stream = assembly.GetManifestResourceStream("NewAppTest.some_data.json");
//Read the data from the stream as a string
using StreamReader reader = new(stream);
string data = reader.ReadToEnd();

谢谢,效果很好。对于所有正在阅读的人:我还创建了一个子文件夹,名为";子文件夹";在测试项目中,并在其中放入some_data.json和more_data.jsson:

subfolder
+ some_data.json
+ more_data.json

在csproj中,我添加了这个以包括所有文件:

<EmbeddedResource Include="subfolder/*.*" />

在测试方法中,我用这个来读取文件:

var assembly = typeof(UnitTest1).Assembly;
using Stream stream =  assembly.GetManifestResourceStream("NewAppTest.subfolder.more_data.json");

这样,当您为测试添加新的数据文件时,就不需要编辑csproj。

最新更新