'Unit Testing a "Catch" in C#

I have created an API project using .NET 6.0. I have configured the app.MapGet method correctly, and they are executing their respective methods. These methods execute their respective Datacalls and return "Results.Ok(results)"

   public static class ResultSetBeingReturned
{
    public static async Task<IResult> ExecuteResultSet<T>(this Task<IEnumerable<T>> task)
    {
        try
        {
            var results = await task;

            if (results == null) return Results.NotFound();

            return Results.Ok(results);
        }
        catch (Exception ex)
        {

            return Results.Problem(ex.Message);
        }
    }
}

I want to unit test this method, so my question is: How do I invoke an API that is going to generate an Exception that is NOT a 404 Not Found?



Solution 1:[1]

By using an IEnumerable<T> which throws an exception in your tests:

public static async Task Main()
{
    var enumerable = Task.Run(() => Error());
    var res = await enumerable.ExecuteResultSet();
    Console.WriteLine(res.GetType().Name); // whatever Result.Problem returns
}

private static IEnumerable<string> Error()
{
    throw new Exception();
}

Live example: https://dotnetfiddle.net/FDT8fs


Another option is simply to use Task.FromException

public static async Task Main()
{
    var res = await Task.FromException<IEnumerable<string>>(new Exception()).ExecuteResultSet();
    Console.WriteLine(res.GetType().Name);
}

Live example: https://dotnetfiddle.net/oezJwI

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Guru Stron