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.
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
class AsyncClient
{
virtual Task<string> GetAsync() => Task.FromResult(string.Empty);
}
var mock = new Mock<AsyncClient>()
.Setup(c => c.GetAsync()).ReturnsAsync(string.Empty);
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.