简体   繁体   中英

NUnit Assert.Throws swallows console output

Here is a sample program to reproduce the issue:

[TestFixture] // NUnit ver. 3.9
public class IssueTest
{
    [Test]
    public void AssertThrowsConsoleIssue()
    {
        Console.WriteLine(1);
        Assert.Throws<Exception>(() =>
        {
            Console.WriteLine(2);
            throw new Exception("test");
        });
        Console.WriteLine(3);
    }
}

I expect an output to be

1
2
3

But in reality it is

1
3

I encountered this issue when was debugging a unit test and noticed that some console log output was missing.

As for me this looks like a bug. Is there a way to prevent Assert.Throws from swallowing Console output?

This is a bug and you just found it! Usually bugs need to be confirmed but seeing your example I can understand exactly what is happening.

Throws creates a temporary test result and context, which we throw away. If we didn't do that, the thrown exception would be recorded in the result. Obviously, we need to save some things, including the text output, from that temporary result. It will be cool if you can file a bug for this on GitHub.

As a workaround, you can use an async delegate as suggested by Roman. If you do that, Assert.Throws will then use different code that doesn't create a throwaway context and result.

If you file a bug on this, I'll try to give you a better workaround on the issue. ;-)

I have the same issue, Roman's hack fixed my problem. Waiting for the next release with the fix :)

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