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?