diff --git a/docs/rules/Moq1300.md b/docs/rules/Moq1300.md index 6d85e25ef..6eb9fa672 100644 --- a/docs/rules/Moq1300.md +++ b/docs/rules/Moq1300.md @@ -70,3 +70,54 @@ dotnet_diagnostic.Moq1300.severity = none For more information, see [How to suppress code analysis warnings](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/suppress-warnings). + +### Advanced Scenarios: Generic Type Parameters + +Moq1300 fires for generic type parameters constrained to interfaces, even though the constraint ensures interface compatibility at the call site: + +```csharp +void SetupMyMock(Mock mock, Action> setupStuff) + where T : IFoo +{ + // Moq1300 fires here, even though T is constrained to IFoo + setupStuff(mock.As()); +} +``` + +#### Why This Happens + +C# generic constraints cannot enforce "interface-only" requirements. While `where T : IFoo` ensures `T` implements the interface `IFoo`, it doesn't prevent `T` from being a class (e.g., `class Foo : IFoo {}`), which would cause `Mock.As()` to fail at runtime. + +Because `Mock.As()` only works with interfaces, the analyzer **errs on the side of safety** and reports this as an error to prevent potential runtime failures. + +#### When Suppression is Appropriate + +- You control all call sites and can verify `T` is always an interface +- Your helper method is internal to your test project with limited usage +- You have integration tests validating the generic patterns + +#### When to Avoid Suppression + +- The helper is in a public library +- Call sites are outside your control +- Runtime failures would be difficult to diagnose + +##### Suppression Example + +```csharp +void SetupMyMock(Mock mock, Action> setupStuff) + where T : IFoo +{ + #pragma warning disable Moq1300 // Helper method used in test where call sites are under our control + setupStuff(mock.As()); + #pragma warning restore Moq1300 +} +``` + +> **Note:** Per [issue #756](https://github.com/rjmurillo/moq.analyzers/issues/756), this guidance may be reconsidered if: +> +>1. multiple independent users report the scenario, +>2. official Moq documentation includes this pattern, +>3. C# adds interface-only constraints, +>4. significant community validation, or +>5. the pattern appears in other major OSS projects