简体   繁体   中英

How to log exception thrown in unit tests without try/catch blocks?

I am using Microsoft.VisualStudio.TestTools.UnitTesting to run my tests in Visual Studio. I am doing logging within all my code in a log file. In [TestInitialize] and [TestCleanup] methods, I am also logging the beginning/ending of tests.

I can log the result of the test through the TestContext.CurrentTestOutcome property. Whenever an exception is thrown WITHIN MY CODE, I log it before throwing it, so my log file has a trace of that exception.

However, I do not know how to log exceptions thrown by DLLs that my code is referencing. Such exceptions are handled by the unit test framework and logged in the test explorer window within Visual Studio.

How can I log those exceptions in my file?

I could surround each of my test cases with a try and log in the catch block. However, as I have many test cases, this is repetitive/painful.

Any idea/solution?

也许您正在寻找ExpectedExceptionAttribute

You could write an extension method that takes an Action and executes it with the appropriate try/catch logic:

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

Then in your test method,

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

        someTest.WithExceptionLogging();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM