Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

.net - How do I test an async method with NUnit (or possibly with another framework)?

I have an ASP.NET Web API application, with an ApiController that features asynchronous methods, returning Task<> objects and marked with the async keyword.

public class MyApiController : ApiController
{
    public async Task<MyData> GetDataById(string id)
    {
        ...
    }
}

How can I write NUnit tests for the ApiController's asynchronous methods? If I need to use another testing framework I'm open for that too. I'm fairly new to .NET unit testing in general, so I'm interested in learning best practices.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As of today (7/2/2014) async testing is supported by:

In the first two frameworks, the test method must have this signature:

[TestMethod]
public async Task MyTestMethod()
{
   ...
   var result = await objectUnderTest.TestedAsyncMethod(...);
   // Make assertions
}

NUnit v2.6.2+ (but before 3.0), apart from that signature, supports this one:

public async void MyTestMethod()

Of course, inside any of these test methods you can use await to call and wait on asynchronous methods.

If you're using a testing framework that doesn't support async test methods, then, the only way to do it, is to call the async method and wait until it finishes running using any of the usual ways: await, reading the Result property of the Task<T> returned by an async method, using any of the usual wait methods of Task and so on. After the awaiting, you can do all the asserts as usual. For example, using MSTest:

[TestMethod]
public void MyTestMethod()
{
    ...
    Task<MyResultClass> task = objectUnderTest.MyAsyncMethod(...);
    // Make anything that waits for the method to end
    MyResultClass result = task.Result;

    // Make the assertions
    Assert.IsNotNull(result);
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...