rjmurillo/moq.analyzers

View on GitHub
docs/rules/Moq1300.md

Summary

Maintainability
Test Coverage
# Moq1300: `Mock.As()` should take interfaces only

| Item     | Value |
| -------- | ----- |
| Enabled  | True  |
| Severity | Error |
| CodeFix  | False |
---

The `.As()` method is used when a mocked object must implement multiple interfaces. It cannot be used with abstract or
concrete classes. To fix:

- Change the method to use an interface
- Remove the `.As()` method

## Examples of patterns that are flagged by this analyzer

```csharp
interface ISampleInterface
{
    int Calculate(int a, int b);
}

class SampleClass
{
    int Calculate() => 0;
}

var mock = new Mock<SampleClass>()
    .As<SampleClass>(); // Moq1300: Mock.As() should take interfaces only
```

## Solution

```csharp
interface ISampleInterface
{
    int Calculate(int a, int b);
}

class SampleClass
{
    int Calculate() => 0;
}

var mock = new Mock<ISampleInterface>();
```

## 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.

```csharp
#pragma warning disable Moq1300
var mock = new Mock<SampleClass>()
    .As<SampleClass>(); // Moq1300: Mock.As() should take interfaces only
#pragma warning restore Moq1300
```

To disable the rule for a file, folder, or project, set its severity to `none`
in the
[configuration file](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/configuration-files).

```ini
[*.{cs,vb}]
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).