Skip to content

Latest commit

 

History

History
74 lines (56 loc) · 2.16 KB

Moq1410.md

File metadata and controls

74 lines (56 loc) · 2.16 KB

Moq1410: Explicitly set the Strict mocking behavior

Moq1410: Explicitly set the Strict mocking behavior

Item Value
Enabled True
Severity Info
CodeFix True

Mocks use the MockBehavior.Loose by default. Some people find this default behavior undesirable, as it can lead to unexpected behavior if the mock is improperly set up. To fix, specify MockBehavior.Strict to cause Moq to always throw an exception for invocations that don't have a corresponding setup.

Examples of patterns that are flagged by this analyzer

interface ISample
{
    int Calculate() => 0;
}

var mock = new Mock<ISample>(); // Moq1410: Moq: Explicitly set the Strict mocking behavior
var mock2 = Mock.Of<ISample>();  // Moq1410: Moq: Explicitly set the Strict mocking behavior
interface ISample
{
    int Calculate() => 0;
}

var mock = new Mock<ISample>(MockBehavior.Default); // Moq1410: Explicitly set the Strict mocking behavior
var mock2 = Mock.Of<ISample>(MockBehavior.Default); // Moq1410: Explicitly set the Strict mocking behavior
var repo = new MockRepository(MockBehavior.Default); // Moq1410: Explicitly set the Strict mocking behavior

Solution

interface ISample
{
    int Calculate() => 0;
}

var mock = new Mock<ISample>(MockBehavior.Strict);
var mock2 = Mock.Of<ISample>(MockBehavior.Strict);
var repo = new MockRepository(MockBehavior.Strict);

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 Moq1410
var mock = new Mock<ISample>(); // Moq1410: Moq: Explicitly set the Strict mocking behavior
#pragma warning restore Moq1410

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

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

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