Skip to content

Commit 93e2f6c

Browse files
authored
Add new rule to enforce MockBehavior.Strict (Moq1410) (#302)
Introduced a new rule Moq1410, to enforce setting the MockBehavior to Strict in Mock declarations. This is set as Info and can be elevated in `.editorconfig`. Fixes #127 Related to #296 from @MattKotsenas (Thanks Matt!) Changes: - Introduced a new abstract class for analyzing `MockBehavior` so code can be shared between Matt's implementation and this. - Added a new diagnostic analyzer (`Moq1410`) to enforce explicit strict mocking behavior. - Introduced a code fix provider for handling diagnostics related to strict mock behavior. - Enhanced encapsulation by changing public members to internal in the `MoqKnownSymbols` class.
1 parent 4cf69db commit 93e2f6c

13 files changed

Lines changed: 529 additions & 148 deletions

‎docs/rules/Moq1410.md‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Moq1410: Explicitly set the Strict mocking behavior
2+
3+
# Moq1410: Explicitly set the Strict mocking behavior
4+
5+
| Item | Value |
6+
| -------- | ------- |
7+
| Enabled | True |
8+
| Severity | Info |
9+
| CodeFix | True |
10+
11+
---
12+
13+
Mocks use the `MockBehavior.Loose` by default. Some people find this default behavior undesirable, as it can lead to
14+
unexpected behavior if the mock is improperly set up. To fix, specify `MockBehavior.Strict` to cause Moq to always throw
15+
an exception for invocations that don't have a corresponding setup.
16+
17+
## Examples of patterns that are flagged by this analyzer
18+
19+
```csharp
20+
interface ISample
21+
{
22+
int Calculate() => 0;
23+
}
24+
25+
var mock = new Mock<ISample>(); // Moq1410: Moq: Explicitly set the Strict mocking behavior
26+
var mock2 = Mock.Of<ISample>(); // Moq1410: Moq: Explicitly set the Strict mocking behavior
27+
```
28+
29+
```csharp
30+
interface ISample
31+
{
32+
int Calculate() => 0;
33+
}
34+
35+
var mock = new Mock<ISample>(MockBehavior.Default); // Moq1410: Explicitly set the Strict mocking behavior
36+
var mock2 = Mock.Of<ISample>(MockBehavior.Default); // Moq1410: Explicitly set the Strict mocking behavior
37+
var repo = new MockRepository(MockBehavior.Default); // Moq1410: Explicitly set the Strict mocking behavior
38+
```
39+
40+
## Solution
41+
42+
```csharp
43+
interface ISample
44+
{
45+
int Calculate() => 0;
46+
}
47+
48+
var mock = new Mock<ISample>(MockBehavior.Strict);
49+
var mock2 = Mock.Of<ISample>(MockBehavior.Strict);
50+
var repo = new MockRepository(MockBehavior.Strict);
51+
```
52+
53+
## Suppress a warning
54+
55+
If you just want to suppress a single violation, add preprocessor directives to
56+
your source file to disable and then re-enable the rule.
57+
58+
```csharp
59+
#pragma warning disable Moq1410
60+
var mock = new Mock<ISample>(); // Moq1410: Moq: Explicitly set the Strict mocking behavior
61+
#pragma warning restore Moq1410
62+
```
63+
64+
To disable the rule for a file, folder, or project, set its severity to `none`
65+
in the
66+
[configuration file](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/configuration-files).
67+
68+
```ini
69+
[*.{cs,vb}]
70+
dotnet_diagnostic.Moq1410.severity = none
71+
```
72+
73+
For more information, see
74+
[How to suppress code analysis warnings](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/suppress-warnings).

‎docs/rules/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,4 @@
1111
| [Moq1201](./Moq1201.md) | Setup of async methods should use `.ReturnsAsync` instance instead of `.Result` |
1212
| [Moq1300](./Moq1300.md) | `Mock.As()` should take interfaces only |
1313
| [Moq1400](./Moq1400.md) | Explicitly choose a mocking behavior instead of relying on the default (Loose) behavior |
14+
| [Moq1400](./Moq1410.md) | Explicitly set the Strict mocking behavior |

‎src/Analyzers/AnalyzerReleases.Unshipped.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,5 @@
55

66
Rule ID | Category | Severity | Notes
77
--------|----------|----------|-------
8-
Moq1400 | Moq | Warning | SetExplicitMockBehaviorAnalyzer, [Documentation](https://github.com/rjmurillo/moq.analyzers/blob/main/docs/rules/Moq1400.md)
8+
Moq1400 | Moq | Warning | SetExplicitMockBehaviorAnalyzer, [Documentation](https://github.com/rjmurillo/moq.analyzers/blob/main/docs/rules/Moq1400.md)
9+
Moq1410 | Moq | Info | SetStrictMockBehaviorAnalyzer, [Documentation](https://github.com/rjmurillo/moq.analyzers/blob/main/docs/rules/Moq1410.md)
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
using Microsoft.CodeAnalysis.Operations;
2+
3+
namespace Moq.Analyzers;
4+
5+
/// <summary>
6+
/// Serves as a base class for diagnostic analyzers that analyze mock behavior in Moq.
7+
/// </summary>
8+
/// <remarks>
9+
/// This abstract class provides common functionality for analyzing Moq's MockBehavior, such as registering
10+
/// compilation start actions and defining the core analysis logic to be implemented by derived classes.
11+
/// </remarks>
12+
public abstract class MockBehaviorDiagnosticAnalyzerBase : DiagnosticAnalyzer
13+
{
14+
/// <inheritdoc />
15+
public override void Initialize(AnalysisContext context)
16+
{
17+
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
18+
context.EnableConcurrentExecution();
19+
20+
context.RegisterCompilationStartAction(RegisterCompilationStartAction);
21+
}
22+
23+
internal abstract void AnalyzeCore(OperationAnalysisContext context, IMethodSymbol target, ImmutableArray<IArgumentOperation> arguments, MoqKnownSymbols knownSymbols);
24+
25+
private void RegisterCompilationStartAction(CompilationStartAnalysisContext context)
26+
{
27+
MoqKnownSymbols knownSymbols = new(context.Compilation);
28+
29+
// Ensure Moq is referenced in the compilation
30+
if (!knownSymbols.IsMockReferenced())
31+
{
32+
return;
33+
}
34+
35+
// Look for the MockBehavior type and provide it to Analyze to avoid looking it up multiple times.
36+
if (knownSymbols.MockBehavior is null)
37+
{
38+
return;
39+
}
40+
41+
context.RegisterOperationAction(context => AnalyzeObjectCreation(context, knownSymbols), OperationKind.ObjectCreation);
42+
43+
context.RegisterOperationAction(context => AnalyzeInvocation(context, knownSymbols), OperationKind.Invocation);
44+
}
45+
46+
private void AnalyzeObjectCreation(OperationAnalysisContext context, MoqKnownSymbols knownSymbols)
47+
{
48+
if (context.Operation is not IObjectCreationOperation creation)
49+
{
50+
return;
51+
}
52+
53+
if (creation.Type is null ||
54+
creation.Constructor is null ||
55+
!(creation.Type.IsInstanceOf(knownSymbols.Mock1) || creation.Type.IsInstanceOf(knownSymbols.MockRepository)))
56+
{
57+
// We could expand this check to include any method that accepts a MockBehavior parameter.
58+
// Leaving it narrowly scoped for now to avoid false positives and potential performance problems.
59+
return;
60+
}
61+
62+
AnalyzeCore(context, creation.Constructor, creation.Arguments, knownSymbols);
63+
}
64+
65+
private void AnalyzeInvocation(OperationAnalysisContext context, MoqKnownSymbols knownSymbols)
66+
{
67+
if (context.Operation is not IInvocationOperation invocation)
68+
{
69+
return;
70+
}
71+
72+
if (!invocation.TargetMethod.IsInstanceOf(knownSymbols.MockOf, out IMethodSymbol? match))
73+
{
74+
// We could expand this check to include any method that accepts a MockBehavior parameter.
75+
// Leaving it narrowly scoped for now to avoid false positives and potential performance problems.
76+
return;
77+
}
78+
79+
AnalyzeCore(context, match, invocation.Arguments, knownSymbols);
80+
}
81+
}

‎src/Analyzers/SetExplicitMockBehaviorAnalyzer.cs‎

Lines changed: 2 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ namespace Moq.Analyzers;
77
/// Mock should explicitly specify a behavior and not rely on the default.
88
/// </summary>
99
[DiagnosticAnalyzer(LanguageNames.CSharp)]
10-
public class SetExplicitMockBehaviorAnalyzer : DiagnosticAnalyzer
10+
public class SetExplicitMockBehaviorAnalyzer : MockBehaviorDiagnosticAnalyzerBase
1111
{
1212
private static readonly LocalizableString Title = "Moq: Explicitly choose a mock behavior";
1313
private static readonly LocalizableString Message = "Explicitly choose a mocking behavior instead of relying on the default (Loose) behavior";
@@ -25,73 +25,8 @@ public class SetExplicitMockBehaviorAnalyzer : DiagnosticAnalyzer
2525
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule);
2626

2727
/// <inheritdoc />
28-
public override void Initialize(AnalysisContext context)
29-
{
30-
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
31-
context.EnableConcurrentExecution();
32-
33-
context.RegisterCompilationStartAction(RegisterCompilationStartAction);
34-
}
35-
36-
private static void RegisterCompilationStartAction(CompilationStartAnalysisContext context)
37-
{
38-
MoqKnownSymbols knownSymbols = new(context.Compilation);
39-
40-
// Ensure Moq is referenced in the compilation
41-
if (!knownSymbols.IsMockReferenced())
42-
{
43-
return;
44-
}
45-
46-
// Look for the MockBehavior type and provide it to Analyze to avoid looking it up multiple times.
47-
if (knownSymbols.MockBehavior is null)
48-
{
49-
return;
50-
}
51-
52-
context.RegisterOperationAction(context => AnalyzeObjectCreation(context, knownSymbols), OperationKind.ObjectCreation);
53-
54-
context.RegisterOperationAction(context => AnalyzeInvocation(context, knownSymbols), OperationKind.Invocation);
55-
}
56-
57-
private static void AnalyzeObjectCreation(OperationAnalysisContext context, MoqKnownSymbols knownSymbols)
58-
{
59-
if (context.Operation is not IObjectCreationOperation creation)
60-
{
61-
return;
62-
}
63-
64-
if (creation.Type is null ||
65-
creation.Constructor is null ||
66-
!(creation.Type.IsInstanceOf(knownSymbols.Mock1) || creation.Type.IsInstanceOf(knownSymbols.MockRepository)))
67-
{
68-
// We could expand this check to include any method that accepts a MockBehavior parameter.
69-
// Leaving it narrowly scoped for now to avoid false positives and potential performance problems.
70-
return;
71-
}
72-
73-
AnalyzeCore(context, creation.Constructor, creation.Arguments, knownSymbols);
74-
}
75-
76-
private static void AnalyzeInvocation(OperationAnalysisContext context, MoqKnownSymbols knownSymbols)
77-
{
78-
if (context.Operation is not IInvocationOperation invocation)
79-
{
80-
return;
81-
}
82-
83-
if (!invocation.TargetMethod.IsInstanceOf(knownSymbols.MockOf, out IMethodSymbol? match))
84-
{
85-
// We could expand this check to include any method that accepts a MockBehavior parameter.
86-
// Leaving it narrowly scoped for now to avoid false positives and potential performance problems.
87-
return;
88-
}
89-
90-
AnalyzeCore(context, match, invocation.Arguments, knownSymbols);
91-
}
92-
9328
[SuppressMessage("Design", "MA0051:Method is too long", Justification = "Should be fixed. Ignoring for now to avoid additional churn as part of larger refactor.")]
94-
private static void AnalyzeCore(OperationAnalysisContext context, IMethodSymbol target, ImmutableArray<IArgumentOperation> arguments, MoqKnownSymbols knownSymbols)
29+
internal override void AnalyzeCore(OperationAnalysisContext context, IMethodSymbol target, ImmutableArray<IArgumentOperation> arguments, MoqKnownSymbols knownSymbols)
9530
{
9631
// Check if the target method has a parameter of type MockBehavior
9732
IParameterSymbol? mockParameter = target.Parameters.DefaultIfNotSingle(parameter => parameter.Type.IsInstanceOf(knownSymbols.MockBehavior));
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
using System.Diagnostics.CodeAnalysis;
2+
using Microsoft.CodeAnalysis.Operations;
3+
4+
namespace Moq.Analyzers;
5+
6+
/// <summary>
7+
/// Mock should explicitly specify Strict behavior.
8+
/// </summary>
9+
[DiagnosticAnalyzer(LanguageNames.CSharp)]
10+
public class SetStrictMockBehaviorAnalyzer : MockBehaviorDiagnosticAnalyzerBase
11+
{
12+
private static readonly LocalizableString Title = "Moq: Set MockBehavior to Strict";
13+
private static readonly LocalizableString Message = "Explicitly set the Strict mocking behavior";
14+
15+
private static readonly DiagnosticDescriptor Rule = new(
16+
DiagnosticIds.SetStrictMockBehavior,
17+
Title,
18+
Message,
19+
DiagnosticCategory.Moq,
20+
DiagnosticSeverity.Info,
21+
isEnabledByDefault: true,
22+
helpLinkUri: $"https://github.com/rjmurillo/moq.analyzers/blob/{ThisAssembly.GitCommitId}/docs/rules/{DiagnosticIds.SetStrictMockBehavior}.md");
23+
24+
/// <inheritdoc />
25+
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule);
26+
27+
/// <inheritdoc />
28+
[SuppressMessage("Design", "MA0051:Method is too long", Justification = "Should be fixed. Ignoring for now to avoid additional churn as part of larger refactor.")]
29+
internal override void AnalyzeCore(OperationAnalysisContext context, IMethodSymbol target, ImmutableArray<IArgumentOperation> arguments, MoqKnownSymbols knownSymbols)
30+
{
31+
// Check if the target method has a parameter of type MockBehavior
32+
IParameterSymbol? mockParameter = target.Parameters.DefaultIfNotSingle(parameter => parameter.Type.IsInstanceOf(knownSymbols.MockBehavior));
33+
34+
// If the target method doesn't have a MockBehavior parameter, check if there's an overload that does
35+
if (mockParameter is null && target.TryGetOverloadWithParameterOfType(knownSymbols.MockBehavior!, out IMethodSymbol? methodMatch, out _, cancellationToken: context.CancellationToken))
36+
{
37+
if (!methodMatch.TryGetParameterOfType(knownSymbols.MockBehavior!, out IParameterSymbol? parameterMatch, cancellationToken: context.CancellationToken))
38+
{
39+
return;
40+
}
41+
42+
ImmutableDictionary<string, string?> properties = new DiagnosticEditProperties
43+
{
44+
TypeOfEdit = DiagnosticEditProperties.EditType.Insert,
45+
EditPosition = parameterMatch.Ordinal,
46+
}.ToImmutableDictionary();
47+
48+
// Using a method that doesn't accept a MockBehavior parameter, however there's an overload that does
49+
context.ReportDiagnostic(context.Operation.CreateDiagnostic(Rule, properties));
50+
return;
51+
}
52+
53+
IArgumentOperation? mockArgument = arguments.DefaultIfNotSingle(argument => argument.Parameter.IsInstanceOf(mockParameter));
54+
55+
// Is the behavior set via a default value?
56+
if (mockArgument?.ArgumentKind == ArgumentKind.DefaultValue && mockArgument.Value.WalkDownConversion().ConstantValue.Value == knownSymbols.MockBehaviorDefault?.ConstantValue)
57+
{
58+
if (!target.TryGetParameterOfType(knownSymbols.MockBehavior!, out IParameterSymbol? parameterMatch, cancellationToken: context.CancellationToken))
59+
{
60+
return;
61+
}
62+
63+
ImmutableDictionary<string, string?> properties = new DiagnosticEditProperties
64+
{
65+
TypeOfEdit = DiagnosticEditProperties.EditType.Insert,
66+
EditPosition = parameterMatch.Ordinal,
67+
}.ToImmutableDictionary();
68+
69+
context.ReportDiagnostic(context.Operation.CreateDiagnostic(Rule, properties));
70+
return;
71+
}
72+
73+
// NOTE: This logic can't handle indirection (e.g. var x = MockBehavior.Default; new Mock(x);)
74+
//
75+
// The operation specifies a MockBehavior; is it MockBehavior.Strict?
76+
if (mockArgument?.Value.WalkDownConversion().ConstantValue.Value != knownSymbols.MockBehaviorStrict?.ConstantValue
77+
&& mockArgument?.DescendantsAndSelf().OfType<IFieldReferenceOperation>().Any(argument => argument.Member.IsInstanceOf(knownSymbols.MockBehaviorStrict)) != true)
78+
{
79+
if (!target.TryGetParameterOfType(knownSymbols.MockBehavior!, out IParameterSymbol? parameterMatch, cancellationToken: context.CancellationToken))
80+
{
81+
return;
82+
}
83+
84+
ImmutableDictionary<string, string?> properties = new DiagnosticEditProperties
85+
{
86+
TypeOfEdit = DiagnosticEditProperties.EditType.Replace,
87+
EditPosition = parameterMatch.Ordinal,
88+
}.ToImmutableDictionary();
89+
90+
context.ReportDiagnostic(context.Operation.CreateDiagnostic(Rule, properties));
91+
}
92+
}
93+
}

‎src/CodeFixes/BehaviorType.cs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
namespace Moq.CodeFixes;
2+
3+
/// <summary>
4+
/// Options to customize the behavior of Moq.
5+
/// </summary>
6+
/// <remarks>
7+
/// Local copy of Moq's MockBehavior enum to avoid dependency on Moq library.
8+
/// </remarks>
9+
internal enum BehaviorType
10+
{
11+
/// <summary>
12+
/// Will never throw exceptions, returning default values when necessary
13+
/// (<see langword="null" /> for reference types, zero for value types,
14+
/// or empty for enumerables and arrays).
15+
/// </summary>
16+
Loose,
17+
18+
/// <summary>
19+
/// Causes Moq to always throw an exception for invocations that don't have
20+
/// a corresponding Setup.
21+
/// </summary>
22+
Strict,
23+
}

0 commit comments

Comments
 (0)