Possible Duplicate:
How do I test an async method with NUnit, eventually with another framework?
What I would like to know is how I can assert that an asynchronous method throws an exception, in a C# unit test? I am able to write asynchronous unit tests with Microsoft.VisualStudio.TestTools.UnitTesting
in Visual Studio 2012, but have not figured out how to test for exceptions. I know that xUnit.net also supports asynchronous test methods in this way, although I haven't tried that framework yet.
For an example of what I mean, the following code defines the system under test:
using System;
using System.Threading.Tasks;
public class AsyncClass
{
public AsyncClass() { }
public Task<int> GetIntAsync()
{
throw new NotImplementedException();
}
}
This code snippet defines a test TestGetIntAsync
for AsyncClass.GetIntAsync
. This is where I need input on how to accomplish the assertion that GetIntAsync
throws an exception:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
[TestClass]
public class TestAsyncClass
{
[TestMethod]
public async Task TestGetIntAsync()
{
var obj = new AsyncClass();
// How do I assert that an exception is thrown?
var rslt = await obj.GetIntAsync();
}
}
Feel free to employ some other relevant unit test framework than the Visual Studio one, such as xUnit.net, if necessary or you would argue that it's a better option.