Skip to content

Instantly share code, notes, and snippets.

@ritalin
Created June 13, 2012 02:48
Show Gist options
  • Save ritalin/2921507 to your computer and use it in GitHub Desktop.
Save ritalin/2921507 to your computer and use it in GitHub Desktop.
Awaitable Assert.Throws implementation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Samples {
public static class AssertPlus {
public static async Task Throws<TException>(Func<Task> inTestCallback) where TException: Exception {
try {
await inTestCallback();
}
catch (Exception ex) {
Assert.That(ex, Is.TypeOf<TException>());
}
}
}
[TestFixture]
public class _AssertPlusをテストするためのTestSuite {
[Test]
public void _TestThrows_Success() {
try {
AssertPlus.Throws<NotSupportedException>(async () => {
await Task.Factory.StartNew(() => {
throw new NotSupportedException();
});
}).GetAwaiter().GetResult();
}
catch {
Assert.Fail("The specified exception is caught.");
}
}
[Test]
public void _TestThrows_Failed_1() {
try {
AssertPlus.Throws<NotSupportedException>(async () => {
await Task.Factory.StartNew(() => {
throw new ArgumentException();
});
}).GetAwaiter().GetResult();
Assert.Fail("Must be failed.");
}
catch {
Assert.Pass("OK");
}
}
[Test]
public void _TestThrows_Failed_2() {
try {
AssertPlus.Throws<NotSupportedException>(async () => {
await Task.Factory.StartNew(() => {
throw new Exception();
});
}).GetAwaiter().GetResult();
Assert.Fail("Must be failed.");
}
catch {
Assert.Pass("OK");
}
}
}
}
@ritalin
Copy link
Author

ritalin commented Jun 13, 2012

Outer GetAwaiter().GetResult() will be replaced to the await syntax using TestSyncContext at https://gist.github.com/2880770

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment