I am using the latest version of NUnit (2.6.2) in Visual Studio 2012 using both resharper and the visual studio test runner. I have the follow sample tests in which I am attempting to verify that an exception is raised on an expected asynchronous method call.
Unfortuantely, this doesn't seem to be working as expected. The first test AsyncTaskCanceledSemiWorking only works because i have the expectedexception attribute. The actual assert is completely ignored (as you can see by the ArgumentOutOfRange exception which is just a fake to get it to fail).
The AsyncTaskCanceledWorking works fine, but doesnt test that the exception is thrown on a specified line, hence less useful.
The third fails majestically with the below....
System.Threading.Tasks.TaskCanceledException : A task was canceled.
Exception doesn't have a stacktrace
Any ideas on how I can test for the TaskCanceledException from a specific line would be very useful.
Thanks
[Test]
[ExpectedException(typeof(TaskCanceledException))]
public async Task AsyncTaskCanceledSemiWorking()
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
cancellationTokenSource.Cancel();
Assert.That(await LongRunningFunction(token), Throws.InstanceOf<ArgumentOutOfRangeException>());
}
[Test]
[ExpectedException(typeof(TaskCanceledException))]
public async Task AsyncTaskCanceledWorking()
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
cancellationTokenSource.Cancel();
int i = await LongRunningFunction(token);
}
[Test]
public async Task AsyncTaskCanceledFailed()
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
cancellationTokenSource.Cancel();
Assert.That(await LongRunningFunction(token), Throws.InstanceOf<TaskCanceledException>());
}
public async Task<int> LongRunningFunction(CancellationToken token)
{
token.ThrowIfCancellationRequested();
await Task.Delay(1000, token);
return 5;
}