MathBunny
MathBunny

Reputation: 956

How to provide a custom error message if a specific exception is thrown in C#/XUnit?

I currently have an integration test where I perform some action, say:

var link = await Blah();

Occasionally, Blah() will throw an exception. I want to record the exception, and if it matches a certain type, I'd like to inform the user of a common potential fix.

My current approach is having a try/catch, but I'm not sure:

  1. What is the XUnit recommended method to output to the user? I'm guessing Console.WriteLine is not good here?

  2. Is there a cleaner approach than having the try/catch? I still need the link value.

Upvotes: 0

Views: 1453

Answers (2)

Fabio
Fabio

Reputation: 32445

Xunit has removed Assert.DoesNotThrow assertion method, which would be appropriate in this case.
You can use combination of Record.Exception and Assert.False methods.

Assert.False, because Assert.IsNotType<T> method doesn't have overload for custom assertion message

var exception = Record.ExceptionAsync(() => Blah());

Assert.False(exception is CertainTypeException, "Shouldn't throw, can fix it with ...");

With FluentAssertion library you can do it as below

Func<Task> callBlah = () => Blah();

await callBlah.Should().NotThrowAsync("Shouldn't throw, can fix it with ...");

Alternative option, which in your case I prefer over previous ones, add information of potential fix to the exception message.

public class MyCertainException : Exception
{
    public MyCertainException (string message) : base($"{message}. Can be fixed with...")
    {

    }
}

With last approach you need do nothing, if exception is thrown, Xunit will display it's message in output results also other developers will see potential fix when see such exception in production or during debugging.

Upvotes: 4

Paul Keister
Paul Keister

Reputation: 13077

It sounds like your test is structured effectively. In order to write information to test output, you'll need to use the ITestOutputHelper interface. XUnit will inject it if the constructor of your test has a parameter of type ITestOutputHelper. See the XUnit docs for details.

Upvotes: 1

Related Questions