【问题标题】:How to load my test data in C#?如何在 C# 中加载我的测试数据?
【发布时间】:2009-07-01 14:28:18
【问题描述】:

我正在努力寻找一种简单的方法来在 C# 中加载我的测试数据。

在 Java 中,我使用以下代码加载资源:

...

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

我尝试使用 C# 资源文件,但我发现加载和操作它很尴尬。有没有更简单的方法在 C# 中加载资源?

【问题讨论】:

    标签: c# nunit testing


    【解决方案1】:

    是 - 使用Assembly.GetManifestResourceStream,例如

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

    只需确保文件在属性中被标记为“嵌入式资源”,以便它们正确内置到程序集中。

    【讨论】:

    • @David Reis 如果像我一样,将测试数据文件放在测试类库内的文件夹中,那么该目录将成为字符串的一部分。例如,如果命名空间是 test.namespace 并且您将 somefile.txt 放在 someDirectory 中,则字符串是 "test.namespace.someDirectory.somefile.txt" 。如果您无法弄清楚字符串,一个有用的方法是this.GetType().Assembly.GetManifestResourceNames()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2013-03-18
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多