Add Assert.Throws support for Task and Task<T>


suppose you have a test like this:

public async void Test1()
var foo = new Foo();
await foo.FailsAsync();

How would you use Assert.Throws to verify foo.Fails throws an expected exception in the most elegant way?

Wrapping that call in Assert.Throws(async () => await foo.FailsAsync()) seems to not do the trick... I could get the task then start, wait and Assert.IsAssignableFrom on the Exception of the task.

I'm not even sure what the ideal syntax would be...


justinc wrote Jul 6, 2012 at 1:53 AM

create an overload of Assert.Throws that matches this signature:

async Task Assert.Throws<TResult, TException>(Func<Task<TResult>> asyncMethod);

justinc wrote Jul 6, 2012 at 5:50 PM

xunit appears to be built against .net 2.0 and neither Func nor Task are available. I tried making a patch but unsure how to proceed with that restriction.

justinc wrote Jul 27, 2012 at 12:35 AM

The workaround is to retrieve the Task and use the Wait() method which will throw and block when called:

public void Test1()
var foo = new Foo();
Assert.Throws(() => foo.FailsAsync().Wait());

BradWilson wrote Aug 4, 2012 at 9:24 PM

Fixed in snapshot 03e3be9a.

gsscoder wrote Feb 16, 2013 at 1:50 PM

to me this not work for me...

Try to write a unit test for https://github.com/gsscoder/httphelpers/blob/master/src/HttpHelpers/HttpParser.cs#L45

Working version (still in working copy) as a guard clause that throws an ArgumentNullException if stream is null.

Regards, Giacomo

gsscoder wrote Feb 16, 2013 at 1:56 PM

Solved in light speed! I rembered this

Install-Package AssertEx -Pre
  () => HttpParser.ParseMessageAsync(stream, (segm0, segm1, segm2) => { }, (header, value) => { }));