Ilya Chernomordik
Ilya Chernomordik

Reputation: 30175

Is it possible to wrap each test execution in XUnit?

I have an exception being thrown by multiple tests that contain some useful information. By default the failed unit test log does not contain that information since it is a property of a custom exception.

I can do this:

try
{
   // Run code that casts MyException
}
catch (MyException e)
{
   // Extra logging for e.SomeProperty
   throw;
}

But then I will have to do this for each and every test. Is there somewhere I can do this for all of the tests of a test class? Kind of like a middleware in Asp.Net.

Or some alternative way to handle exception before XUnit.

Upvotes: 0

Views: 245

Answers (1)

Emik
Emik

Reputation: 36

If MyException is a type you define, you may want to consider changing Exception.Message to be a concatenation of what the user puts in, and the useful information, since generally you want to make the Message be as helpful to you as possible.

public class MyException : Exception
{
    public MyException(string message)
        : base($"{message}: {SomeProperty}") { }

    // other constructors...

    public required object SomeProperty { get; init; }
}

If however you cannot or don't want to, you could also have a helper function for your tests that uses a callback within a try-catch and rethrow the exception with more appropriate information. Exceptions can wrap inside other exceptions which allows each exception to be shown.

static void Do(Action act)
{
    try
    {
        act();
    }
    catch (MyException my)
    {
        throw new($"something something foobar: {my.SomeProperty}", my);
    }
}

(Bare in mind some linters will tell you throwing a bare Exception is bad, but for tests it shouldn't matter.)

You can finally use it in your tests like so:

[Fact]
void Foo() => Do(() =>
{
    // your function goes here!
    // you can simply throw the exception to test out how it'll look like
    throw new MyException("yay") { SomeProperty = "context value" };
});

Upvotes: 1

Related Questions