How can I assert that a C# async method throws an

2020-05-27 02:11发布

问题:

This question already has answers here:
Closed 7 years ago.

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.

回答1:

Please try mark method with:

[ExpectedException(typeof(NotImplementedException))]


回答2:

1st Option would be:

try
{
   await obj.GetIntAsync();
   Assert.Fail("No exception was thrown");
}
catch (NotImplementedException e)
{      
   Assert.Equal("Exception Message Text", e.Message);
}

2nd Option would be to use the Expected Exception Attribute:

[ExpectedException(typeof(NotImplementedException))]

3rd Option would be to use the Assert.Throws :

Assert.Throws<NotImplementedException>(delegate { obj.GetIntAsync(); });


回答3:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;

[TestClass]
public class TestAsyncClass
{
    [TestMethod]
    [ExpectedException(typeof(NotImplementedException))]
    public async Task TestGetIntAsync()
    {
        var obj = new AsyncClass();
        // How do I assert that an exception is thrown?
        var rslt = await obj.GetIntAsync();
    }
}


回答4:

Try use TPL:

[ExpectedException(typeof(NotImplementedException))]
[TestMethod]
public void TestGetInt()
{
    TaskFactory.FromAsync(client.BeginGetInt, client.EndGetInt, null, null)
               .ContinueWith(result =>
                   {
                       Assert.IsNotNull(result.Exception);
                   }
}