How to load my test data in C#?

2020-06-06 04:42发布

I am struggling to find an easy way to load my test data in C#.

In Java, I load a resource using the following code:

...

public static InputStream loadResource(String resource) throws LoadException {
    InputStream is = TestUtils.class.getResourceAsStream(resource);

    if (is == null) {
        throw new LoadException("Error loading '" + resource + "'");
    }

    return is;
}

...

public static void main(String[] args) {
    InputStream is = TestUtils.loadResource("/resourcelocation");
}

I tried to use C# resource file, but I found awkward to load and manipulate it. Is there a simpler way to load resources in C#?

标签: c# nunit testing
1条回答
家丑人穷心不美
2楼-- · 2020-06-06 05:06

Yes - use Assembly.GetManifestResourceStream, e.g.

typeof(TestClass).Assembly
                 .GetManifestResourceStream("test.namespace.Filename.txt")

Just make sure the files are tagged as "Embedded Resource" in the properties, so they get built into the assembly correctly.

查看更多
登录 后发表回答