How to handle exceptions thrown by Tasks in xUnit .net's Assert.Throws?

后端 未结 2 499
Happy的楠姐
Happy的楠姐 2021-01-01 15:54

The following asynchronous xUnit.net test with a lambda marked with the async modifier fails by reporting that no exception was thrown

2条回答
  •  别那么骄傲
    2021-01-01 16:15

    If you also need to return the exception to verify it then this might be useful:

    public static async Task AssertThrowsAsync(Func func)
        {
            var expected = typeof (TException);
            Exception exception = null;
            Type actual = null;
            try
            {
                await func();
            }
            catch (Exception e)
            {
                actual = e.GetType();
                exception = e;
            }
            Assert.NotNull(exception);
            Assert.Equal(expected, actual);
            return exception;
        }
    

提交回复
热议问题