简体   繁体   中英

Asynchronous Unit Testing - async/await vs. Task.Result

My solution architect and I were discussing the correct way to unit test the asynchronous code.

He prefers using void [Test] methods, and asserting Task.Result , while I feel that asynchronous methods should be tested with async/await [Test] methods.

Somehow, I feel that using Task.Result is incorrect way to testing the asynchronous code, but can't justify or pin-point exactly why?

For example, given the below code:

    public class SomeService 
    {
        public async Task<bool> ProcessSomething(string request)
        {
           return await Repository.Save(request);
        }
    }

Method 1: Task.Result

    [Test]
    public void ServiceProcessTest()
    {          
       var sut = new SomeService();

       // Use Task.Result
       var unusedResult= sut.ProcessSomething("Hello world!").Result;
       
       A.CallTo(() => Repository.Save(A<string>>.Ignored)).MustHaveHappenedOnceExactly();
    }

Method 2: async/await

    [Test]
    public async Task ServiceProcessTest()
    {          
       var sut = new SomeService();

       // Use async/await
       var unusedResult= await sut.ProcessSomething("Hello world!");
       
       A.CallTo(() => Repository.Save(A<string>>.Ignored)).MustHaveHappenedOnceExactly();
    }

Which once should we be using, and why? If both are correct, then are there times when one is preferred over the other?

As others have pointed out in the comments, always use async/await if you can, since Task.Result can cause deadlocks . Also, the unit test should reflect how you use the System Under Test (SUT) from production code.

The only circumstance when you should use Task.Result IMO, is when introducing a function/object that returns a Task in legacy code and you aren't in the position (yet) to make the calling method async , so you are forced to use Task.Result to execute the Task .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM