Skip to content

Latest commit

 

History

History
59 lines (45 loc) · 1.79 KB

Moq1201.md

File metadata and controls

59 lines (45 loc) · 1.79 KB

Moq1201: Setup of async methods should use .ReturnsAsync instance instead of .Result

Item Value
Enabled True
Severity Error
CodeFix False

Moq now supports the .ReturnsAsync() method to support mocking async methods. Use it instead of returning .Result, which can cause issues.

Examples of patterns that are flagged by this analyzer

class AsyncClient
{
    virtual Task<string> GetAsync() => Task.FromResult(string.Empty);
}

var mock = new Mock<AsyncClient>()
    .Setup(c => c.GetAsync().Result); // Moq1201: Setup of async methods should use .ReturnsAsync instance instead of .Result

Solution

class AsyncClient
{
    virtual Task<string> GetAsync() => Task.FromResult(string.Empty);
}

var mock = new Mock<AsyncClient>()
    .Setup(c => c.GetAsync()).ReturnsAsync(string.Empty);

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable Moq1201
var mock = new Mock<AsyncClient>()
    .Setup(c => c.GetAsync().Result); // Moq1201: Setup of async methods should use .ReturnsAsync instance instead of .Result
#pragma warning restore Moq1201

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.Moq1201.severity = none

For more information, see How to suppress code analysis warnings.