Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions docs/rules/Moq1300.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(Mock<IFoo> mock, Action<Mock<T>> setupStuff)
where T : IFoo
{
// Moq1300 fires here, even though T is constrained to IFoo
setupStuff(mock.As<T>());
}
```

#### 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<T>()` to fail at runtime.

Because `Mock.As<T>()` 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<T>(Mock<IFoo> mock, Action<Mock<T>> setupStuff)
where T : IFoo
{
#pragma warning disable Moq1300 // Helper method used in test where call sites are under our control
setupStuff(mock.As<T>());
#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
Loading