c# - NUnit 的奇怪行为,ExpectedException & yield return

标签 c# testing nunit yield expected-exception

我在测试中有一个奇怪的行为,我想测试当 null 作为参数传入时是否抛出异常。当我运行测试时,我从 NUnit 获得:

    System.ArgumentNullException was expected
    -- Exception doesn't have a stack trace -- 

我的测试:

[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void Should_not_retrieve_any_fields_when_file_is_null()
{
    _creator.CreateFields(null);
}

我的实现:

public IEnumerable<ImportField> CreateFields(HttpPostedFileBase file)
{
    if (file == null) throw new ArgumentNullException("file");

    using (var reader = new StreamReader(file.InputStream))
    {
        var firstLine = reader.ReadLine();
        var columns = firstLine.Split(new[] { ',' });

        for (var i = 0; i < columns.Length; i++)
        {
            yield return new ImportField(columns[i], i);
        }
    }
}

是否有对此行为的合乎逻辑的解释,我应该以不同的方式进行实现吗?

最佳答案

您出现此行为的原因是 yield 关键字。使用 yield 时,编译器会为方法生成一个类,其中包含 yield。调用该方法时,控制权无条件返回给调用者。您的方法中的任何内容都不会在需要之前实际执行。

如果您将 using 语句提取到一个单独的方法中并返回结果,您的测试就会通过。或者您可以将结果存储到测试中的变量中,例如在其上调用“ToList()”。

    public IEnumerable<ImportField> CreateFields(HttpPostedFileBase file)
    {
        if (file == null) throw new ArgumentNullException("file");

        return ExtractFromFile(file);
    }

    private IEnumerable<ImportField> ExtractFromFile(HttpPostedFileBase file)
    {
        using (var reader = new StreamReader(file.InputStream))
        {
            var firstLine = reader.ReadLine();
            var columns = firstLine.Split(new[] { ',' });

            for (var i = 0; i < columns.Length; i++)
            {
                yield return new ImportField(columns[i], i);
            }
        }
    }

关于c# - NUnit 的奇怪行为,ExpectedException & yield return,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8278491/

相关文章:

c# - C# 中 RectangleShape 的边框样式

git - 如何在Node配置中获取Jenkins中的git标签名称

c# - .Net 等效于 TTimer Delphi 组件

c# - 必填字段验证器文本定位

android - 插桩测试无法在具有 Kotlin 文件的 Android 库模块中运行

typescript - Testcafe:出现错误:无法隐式解析测试运行

function - Perl - getlogin、getpwuid 和 $<

nunit - 尝试在 NUnit 中使用 Moles。获取 "Moles requires tests to be an instrumented process"

c# - 在 NUnit 中测试不可编译的代码

c# - 在数据库中存储图像