如何在没有try / catch块的情况下记录单元测试中抛出的异常?

时间:2014-03-12 00:16:50

标签: c# unit-testing exception logging visual-studio-2013

我正在使用Microsoft.VisualStudio.TestTools.UnitTesting在Visual Studio中运行我的测试。我正在日志文件中记录我的所有代码。在[TestInitialize]和[TestCleanup]方法中,我也记录了测试的开始/结束。

我可以通过TestContext.CurrentTestOutcome属性记录测试结果。每当在我的代码中抛出异常时,我会在抛出它之前记录它,因此我的日志文件会跟踪该异常。

但是,我不知道如何记录我的代码引用的DLL引发的异常。此类异常由单元测试框架处理,并记录在Visual Studio中的测试资源管理器窗口中。

如何在文件中记录这些异常?

我可以尝试围绕每个测试用例并登录catch块。但是,由于我有很多测试用例,这是重复/痛苦的。

任何想法/解决方案?

2 个答案:

答案 0 :(得分:1)

也许您正在寻找ExpectedExceptionAttribute

答案 1 :(得分:1)

您可以编写一个带有Action的扩展方法,并使用相应的try / catch逻辑执行它:

    public static void WithExceptionLogging(Action testToExecute)
    {
        try
        {
            testToExecute();
        }
        catch (Exception e)
        {
            //logging logic goes here
        }
    }

然后在你的测试方法中,

        Action someTest = () =>
        {
            var expected = 1;
            var actual = Calculator.Add("1+0");
            Assert.AreEqual(expected, actual);
        };

        someTest.WithExceptionLogging();