【问题标题】:Strange behavior with NUnit, ExpectedException & yield returnNUnit、ExpectedException 和产量回报的奇怪行为
【发布时间】:2012-01-06 21:18:32
【问题描述】:

我在一个测试中有一个奇怪的行为,我想测试当 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);
        }
    }
}

对这种行为有合理的解释吗?我应该以不同的方式实现吗?

【问题讨论】:

    标签: c# testing nunit yield expected-exception


    【解决方案1】:

    出现这种行为的原因是由于 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);
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多