Unit Testing: Assert Throw Vs ThrowAsync

Issue Description

After migrating code to the new .NET framework (.NET or .NET Core), existing Unit test cases produces below error,

‘Assert.Throws(Func)’ is obsolete: ‘You must call Assert.ThrowsAsync (and await the result) when testing async code.’

Or

Do not use Assert.Throws() to check for asynchronously thrown exceptions.

AssertThrowsFunc' is obsolete

Resolution

The issue is found to be as per new API improvement and guidelines around Sync and Asynchronous calls and Unit testing around it.

The below assert use to work fine for Synchronous and Async code in the older framework. I did see this working in .NET Core 2.* version.


Assert.Throws<ArgumentNullException>(() => details.GetAccountDetails("9981"));

In the recent framework as per new .NET Core 3.1 or.NET 5, to resolve the issue you must use Assert.ThrowsAsync<T> if the target method is Async.

Please refer this article for more details,

For Asynchronous method

You should use Assert as below,


Assert.ThrowsAsync<T>

For Synchronous method

You should use Assert as below,

Assert.Throws<T>

Example:

I have below sample Asynchronous method ,

 
public async Task<IEnumerable> GetAccountDetailsAsync(string queryString)
        {
            if (string.IsNullOrEmpty(queryString))
            {
                throw new ArgumentNullException();
            }
            else
            {
                return new List<string>();
            }
        }

Below code works fine after performing Assert using ThrowAsync<T>

Assert Throw Vs ThrowAsync

References:

Did I miss anything else in these resolution steps?

Did the above steps resolve your issue? Please sound off your comments below!

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



2 thoughts on “Unit Testing: Assert Throw Vs ThrowAsync

Leave a Reply

Your email address will not be published. Required fields are marked *