【问题标题】:Handling exceptions when running nunit tests from console application从控制台应用程序运行 nunit 测试时处理异常
【发布时间】:2015-06-01 11:47:21
【问题描述】:

我正在尝试使用反射从控制台应用程序运行 nunit 测试用例。我得到一个我的 catch 块没有处理的异常。您能否提供一个建议,如何处理调用的测试方法中的所有异常?

static void Main(string[] args)
{
    // Take all classes of the current assebly to which TestFixture attribute is applied
    var testClasses = Assembly.GetExecutingAssembly().GetTypes().Where(c =>
    {
        var attributes = c.GetCustomAttributes(typeof(TestFixtureAttribute));
        return attributes.Any();
    });
    foreach (var testClass in testClasses)
    {
        var testMethods = testClass.GetMethods().Where(m =>
        {
            var attributes = m.GetCustomAttributes(typeof (TestAttribute));
            return attributes.Any();
        });
        var instance = Activator.CreateInstance(testClass);
        foreach (var method in testMethods)
        {
            try
            {
                Action action = (Action) Delegate.CreateDelegate(typeof (Action), 
                                                                 instance, method);
                action();
            }
            catch (AggregateException ae)
            {
                Console.WriteLine(ae.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}

【问题讨论】:

  • 聚合异常发生在try块中,未被捕获。
  • 异常的stacktrace是什么,是什么类型,异常的信息是什么?

标签: c# exception-handling nunit


【解决方案1】:

真的不清楚你为什么要这样做,因为已经有 nunit-console 可以从控制台应用程序运行单元测试。目前还不清楚您认为没有被捕获的异常,但我怀疑这不是您认为的类型。我把你的代码和一些非常基本的测试一起放入一个新的控制台应用程序中:

[TestFixture]
public class SomeFailingTests
{
    [Test]
    public void Fails()
    {
        Assert.AreEqual(1, 0);
    }

    [Test]
    [ExpectedException(typeof(ArgumentException))]
    public void TestExceptionExpected()
    {
    }

    [Test]
    public void TestThrows()
    {
        throw new InvalidOperationException();
    }

    [Test]
    [ExpectedException(typeof(InvalidOperationException))]
    public void TestThrowsExpected()
    {
        throw new InvalidOperationException();
    }
}

所有抛出异常的测试都被该行捕获:

catch (Exception e)

这是有道理的,因为他们都没有抛出AggregateException。我怀疑你正在运行的任何测试也没有抛出一个,并且也被你的外部捕获物抓住了。一个好的开始可能是将这个块重写为:

catch (Exception e)
{
    Console.WriteLine(string.Format("{0}: {1}", e.GetType().Name, e.Message));
}

这样您就可以看到您没有处理的任何异常类型。例如,在非常基本的层面上,您可能需要考虑 AssertionException

如果您想支持与其他 nunit 运行器类似的功能集,您还需要注意您运行的任何方法上的 ExpectedException 属性,并检查在调用方法。您还需要检查 Ignored 属性...

正如我对this question 的回答中提到的,如果您想捕获所有在程序集中进行测试。

除非您将此作为学习练习来编写,否则您可能需要重新考虑您的方法。

【讨论】:

    猜你喜欢
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多