rjmurillo/moq.analyzers

View on GitHub
docs/rules/Moq1200.md

Summary

Maintainability
Test Coverage
# Moq1200: Setup should be used only for overridable members

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

Mocking requires generating a subclass of the class to be mocked. Methods not marked `virtual` cannot be overridden.
To fix:

- Mock an interface instead of a clas
- Make the method to be mocked `virtual`

```csharp
class SampleClass
{
    int Property { get; set; }
}

var mock = new Mock<SampleClass>()
    .Setup(x => x.Property); // Moq1200: Setup should be used only for overridable members
```

## Solution

```csharp
class SampleClass
{
    virtual int Property { get; set; }
}

var mock = new Mock<SampleClass>()
    .Setup(x => x.Property);
```

## 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 Moq1200
var mock = new Mock<SampleClass>()
    .Setup(x => x.Property); // Moq1200: Setup should be used only for overridable members
#pragma warning restore Moq1200
```

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.Moq1200.severity = none
```

For more information, see
[How to suppress code analysis warnings](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/suppress-warnings).