Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
c101057
Simplify the AsMustBeUsedWithInterfaceAnalyzer unit tests
GillesTourreau Oct 20, 2026
8c08cf1
Refactoring unit tests for SetupSetAnalyzerTest
GillesTourreau Oct 20, 2026
dc70fce
Refactoring of the MockOfAnalyzerTest
GillesTourreau Oct 20, 2026
bf32a6e
Refactoring of the VerifyStaticMethodsRequiresMockParametersAnalyzerT…
GillesTourreau Oct 20, 2026
3dc35d8
Refactoring of the VerifyMustHaveTimesParameterAnalyzerTest unit test
GillesTourreau Oct 20, 2026
13a601b
Refactoring of the ConstructorArgumentsAnalyzerTest unit test
GillesTourreau Oct 20, 2026
7210184
Refactoring the ItArgumentsMustMatchMockedMethodArgumentsAnalyzerTest…
GillesTourreau Oct 20, 2026
84c6fb0
Refactoring SetupProtectedMustBeUsedWithProtectedOrInternalMembersAna…
GillesTourreau Oct 20, 2026
a43ec19
Refactoring of the SetupMustBeUsedOnlyForOverridableMembersAnalyzerTe…
GillesTourreau Oct 20, 2026
edec6c0
Refactoring of the SetupMethodShouldSpecifyOptionalArgumentsAnalyzerT…
GillesTourreau Oct 20, 2026
544f1a3
Refactoring RaiseMethodsAnalyzerTest unit test
GillesTourreau Oct 20, 2026
1a1407d
Refactoring VerifyMustBeUsedOnlyForOverridableMembersAnalyzerTest uni…
GillesTourreau Oct 20, 2026
b786315
Refactoring the MockInstanceShouldBeStrictBehaviorAnalyzerTest unit test
GillesTourreau Oct 20, 2026
99fe6a2
Refactoring the MockClassCanBeUsedOnlyToMockNonSealedClassAnalyzerTes…
GillesTourreau Oct 20, 2026
39601c6
Refactoring CallBackDelegateMustMatchMockedMethodAnalyzerTest unit test
GillesTourreau Oct 20, 2026
34e75b0
Refactoring the CallBackDelegateParametersShouldNotBeIgnoredAnalyzerT…
GillesTourreau Oct 20, 2026
ed46973
Refactoring of the CallBackDelegateShouldBeUsedWithItIsAnyParametersA…
GillesTourreau Oct 20, 2026
be925ec
Refactoring of the ReturnsMethodDelegateMustMatchMockedMethodAnalyzer…
GillesTourreau Oct 20, 2026
734795c
Refactoring of the SetupMethodMustReturnValueWithStrictBehaviorAnalyz…
GillesTourreau Oct 20, 2026
d11b258
Refactoring of the VerifyAllShouldBeCalledAnalyzerTest unit tests
GillesTourreau Oct 20, 2026
b40fbb3
Refactoring of the VerifyShouldBeCalledForVerifiableSetupAnalyzerTest…
GillesTourreau Oct 20, 2026
ab2eb64
Upgrades the version to v2.2.0
GillesTourreau Oct 20, 2026
db74119
Upgrades the StyleCop analyzers version
GillesTourreau Oct 20, 2026
803fd40
Adds the PosInfoMoq2020 rule (fixes #61).
GillesTourreau Oct 21, 2026
2cb02ad
Fix the CI/CD workflows to use the Trusted Publishing
GillesTourreau Oct 21, 2026
e62373d
Fix release workflow
GillesTourreau Oct 21, 2026
5886f15
Fix release workflow
GillesTourreau Oct 21, 2026
c32a5f8
Upgrades NuGet packages
GillesTourreau Nov 7, 2026
bccadfe
Upgrades the xUnit version to v4
GillesTourreau Nov 7, 2026
fc2f2d7
Upgrades the StyleCop version
GillesTourreau Nov 7, 2026
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
3 changes: 3 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## StyleCop

stylecop.documentation.companyName = P.O.S Informatique
stylecop.documentation.copyrightText = Copyright (c) {companyName}. All rights reserved.

# SA1600: Elements should be documented
dotnet_diagnostic.SA1600.severity = none

Expand Down
5 changes: 5 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Copilot Instructions

## Project Guidelines
- When consolidating analyzer unit tests, declare every ValidTestCases and InvalidTestCases scenario explicitly as a string in TheoryData<string> collection expressions. Do not generate cases using loops. Use multiline raw strings for multiline snippets, following SetupMustBeUsedOnlyForOverridableMembersAnalyzerTest and SetupMethodShouldSpecifyOptionalArgumentsAnalyzerTest.
- Use AsMustBeUsedWithInterfaceAnalyzerTest and SetupSetAnalyzerTest as references. Isolate scenarios in TheoryData<string> ValidTestCases and InvalidTestCases, use both via MemberData for Analyze and NoMoqLibrary, use raw interpolated source templates and explicit diagnostic-ID markup, reuse/extend MoqAnalyzersTests.FakeMoqLibrary, preserve coverage, and retain MarkupMode.Ignore only for no-Moq verification.
4 changes: 2 additions & 2 deletions .github/workflows/github-actions-ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7

- name: Setup .NET 8.x
uses: actions/setup-dotnet@v5
uses: actions/setup-dotnet@v6
with:
dotnet-version: '8.x'

Expand Down
21 changes: 17 additions & 4 deletions .github/workflows/github-actions-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ on:
type: string
description: The version of the library
required: true
default: 2.1.0
default: 2.2.0
VersionSuffix:
type: string
description: The version suffix of the library (for example rc.1)
Expand All @@ -17,11 +17,14 @@ run-name: ${{ inputs.VersionSuffix && format('{0}-{1}', inputs.VersionPrefix, in
jobs:
build:
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7

- name: Setup .NET 8.x
uses: actions/setup-dotnet@v5
uses: actions/setup-dotnet@v6
with:
dotnet-version: '8.x'

Expand All @@ -35,5 +38,15 @@ jobs:
--property:VersionSuffix=${{ github.event.inputs.VersionSuffix }}
"src/Moq.Analyzers/Moq.Analyzers.csproj"

- name: NuGet login
uses: NuGet/login@v1
id: nuget_login
with:
user: ${{ secrets.NUGET_USER }}

- name: Publish the package to nuget.org
run: dotnet nuget push "src/Moq.Analyzers/bin/Release/*.nupkg" --api-key "${{ secrets.NUGET_APIKEY }}" --source https://api.nuget.org/v3/index.json
run: |
dotnet nuget push "src/Moq.Analyzers/bin/Release/*.nupkg" \
--api-key "${{steps.nuget_login.outputs.NUGET_API_KEY}}" \
--source https://api.nuget.org/v3/index.json \
--skip-duplicate
6 changes: 0 additions & 6 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,6 @@
<AssemblyName>PosInformatique.$(MSBuildProjectName)</AssemblyName>
<RootNamespace>PosInformatique.$(MSBuildProjectName.Replace(" ", "_"))</RootNamespace>
</PropertyGroup>

<ItemGroup>
<AdditionalFiles Include="..\..\stylecop.json">
<Link>stylecop.json</Link>
</AdditionalFiles>
</ItemGroup>

<!-- Common NuGet packages -->
<ItemGroup>
Expand Down
16 changes: 8 additions & 8 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
<ItemGroup>
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="5.0.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="5.0.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing" Version="1.1.3" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing" Version="1.1.3" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing" Version="1.1.4" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing" Version="1.1.4" />
<PackageVersion Include="Microsoft.CodeAnalysis.Workspaces.Common" Version="5.0.0" />
<PackageVersion Include="Microsoft.Testing.Extensions.CodeCoverage" Version="18.7.0" />
<PackageVersion Include="Microsoft.Testing.Extensions.TrxReport" Version="2.2.3" />
<PackageVersion Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.14.15" />
<PackageVersion Include="Moq" Version="4.20.70" />
<PackageVersion Include="StyleCop.Analyzers" Version="1.2.0-beta.556" />
<PackageVersion Include="xunit.v3.mtp-v2" Version="3.2.2" />
<PackageVersion Include="Microsoft.Testing.Extensions.CodeCoverage" Version="18.12.0" />
<PackageVersion Include="Microsoft.Testing.Extensions.TrxReport" Version="2.5.2" />
<PackageVersion Include="Microsoft.VisualStudio.Threading.Analyzers" Version="18.12.1" />
<PackageVersion Include="Moq" Version="4.21.0" />
<PackageVersion Include="StyleCop.Analyzers" Version="1.3.177-beta" />
<PackageVersion Include="xunit.v3.mtp-v2" Version="4.0.2" />
</ItemGroup>
</Project>
2 changes: 1 addition & 1 deletion PosInformatique.Moq.Analyzers.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
<File Path="global.json" />
<File Path="LICENSE" />
<File Path="README.md" />
<File Path="stylecop.json" />
</Folder>
<Folder Name="/Solution Items/.github/" />
<Folder Name="/Solution Items/.github/workflows/">
Expand Down Expand Up @@ -37,6 +36,7 @@
<File Path="docs/Compilation/PosInfoMoq2017.md" />
<File Path="docs/Compilation/PosInfoMoq2018.md" />
<File Path="docs/Compilation/PosInfoMoq2019.md" />
<File Path="docs/Compilation/PosInfoMoq2020.md" />
</Folder>
<Folder Name="/Solution Items/docs/Design/">
<File Path="docs/design/PosInfoMoq1000.md" />
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,5 @@ All the rules of this category should not be disabled (or changed their severity
| [PosInfoMoq2017: `Mock<T>.Raise()`/`RaiseAsync()` must use parameters matching the event signature.](docs/Compilation/PosInfoMoq2017.md) | The parameters passed to `Raise()` or `RaiseAsync()` must exactly match the parameters of the corresponding event delegate. |
| [PosInfoMoq2018: The first parameter of `Raise()`/`RaiseAsync()` must be an event.](docs/Compilation/PosInfoMoq2018.md) | The first parameter passed to `Raise()` or `RaiseAsync()` must reference an **event** member of the mocked type. |
| [PosInfoMoq2019: `RaiseAsync()` must be used only for events with async handlers (returning `Task`).](docs/Compilation/PosInfoMoq2019.md) | `Mock<T>.RaiseAsync()` must only be used with events whose delegate type returns `Task` (i.e., async events). |
| [PosInfoMoq2020: `CallBase()` must be used only on virtual or override members.](docs/Compilation/PosInfoMoq2020.md) | `CallBase()` can be used only on `virtual` or `override` members (not standard, `abstract` or `sealed`). |

39 changes: 39 additions & 0 deletions docs/Compilation/PosInfoMoq2020.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# PosInfoMoq2020: `CallBase()` must be used only on virtual or override members

| Property | Value |
|-----------------------|----------------------------------------------------------------------|
| **Rule ID** | PosInfoMoq2020 |
| **Title** | `CallBase()` must be used only on virtual or override members |
| **Category** | Compilation |
| **Default severity** | Error |

## Cause

The `CallBase()` method is used on a `Setup()` of a member which is not `virtual` or `override`
(standard, `abstract`, `sealed` or interface members).

## Rule description

`CallBase()` calls the real implementation of the mocked member. Only `virtual` or `override` members
(not `abstract`, not `sealed`) provide an implementation that Moq can call.

## How to fix violations

Remove the `CallBase()` call, or make the member `virtual`.

## Example

```csharp
public class MyClass
{
public virtual int VirtualMethod() => 1;

public int Method() => 1;
}

var mock = new Mock<MyClass>();

mock.Setup(m => m.VirtualMethod()).CallBase(); // Valid

mock.Setup(m => m.Method()).CallBase(); // PosInfoMoq2020
```
9 changes: 8 additions & 1 deletion src/Moq.Analyzers/AnalyzerReleases.Shipped.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
## Release 2.1.0
## Release 2.2.0

### New Rules
Rule ID | Category | Severity | Notes
--------|----------|----------|-------
PosInfoMoq2020 | Compilation | Error | CallBaseMustBeUsedOnlyForOverridableMembersAnalyzer, [Documentation](https://posinformatique.github.io/PosInformatique.Moq.Analyzers/docs/Compilation/PosInfoMoq2020.html)

## Release 2.1.0

### New Rules
Rule ID | Category | Severity | Notes
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
//-----------------------------------------------------------------------
// <copyright file="CallBaseMustBeUsedOnlyForOverridableMembersAnalyzer.cs" company="P.O.S Informatique">
// Copyright (c) P.O.S Informatique. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace PosInformatique.Moq.Analyzers
{
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class CallBaseMustBeUsedOnlyForOverridableMembersAnalyzer : DiagnosticAnalyzer
{
private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
"PosInfoMoq2020",
"The CallBase() method must be used only on virtual or override members",
"The CallBase() method must be used only on virtual or override members which are not abstract or sealed",
"Compilation",
DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The CallBase() method can be used only on virtual or override members which provide an implementation (not abstract, not sealed).",
helpLinkUri: "https://posinformatique.github.io/PosInformatique.Moq.Analyzers/docs/Compilation/PosInfoMoq2020.html");

public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);

public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();

context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression);
}

private static void Analyze(SyntaxNodeAnalysisContext context)
{
var invocationExpression = (InvocationExpressionSyntax)context.Node;

// Quick syntactic check on the CallBase() method name.
if (invocationExpression.Expression is not MemberAccessExpressionSyntax callBaseAccess ||
callBaseAccess.Name.Identifier.ValueText != "CallBase")
{
return;
}

var moqSymbols = MoqSymbols.FromCompilation(context.Compilation);

if (moqSymbols is null)
{
return;
}

var callBaseSymbol = context.SemanticModel.GetSymbolInfo(invocationExpression, context.CancellationToken);

if (callBaseSymbol.Symbol is not IMethodSymbol callBaseMethod || !callBaseMethod.ContainingNamespace.ToDisplayString().StartsWith("Moq", StringComparison.Ordinal))
{
return;
}

var moqExpressionAnalyzer = new MoqExpressionAnalyzer(moqSymbols, context.SemanticModel);

var setupMethod = moqExpressionAnalyzer.ExtractSetupMethod(invocationExpression, context.CancellationToken);

if (setupMethod is null || setupMethod.Members.Count == 0)
{
return;
}

// The first member is the mocked member (the last in the chain).
var member = setupMethod.Members[0];

if (IsVirtualOrOverride(member.Symbol))
{
return;
}

context.ReportDiagnostic(Diagnostic.Create(Rule, callBaseAccess.Name.GetLocation()));
}

private static bool IsVirtualOrOverride(ISymbol symbol)
{
if (symbol.IsAbstract || symbol.IsSealed)
{
return false;
}

return symbol.IsVirtual || symbol.IsOverride;
}
}
}
4 changes: 4 additions & 0 deletions src/Moq.Analyzers/Moq.Analyzers.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
<PackageProjectUrl>https://github.com/PosInformatique/PosInformatique.Moq.Analyzers</PackageProjectUrl>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageReleaseNotes>
2.2.0
- Add new rules:
- PosInfoMoq2020: CallBase() must be used only on virtual or override members.

2.1.0
- Add new rules:
- PosInfoMoq1011: The Setup() expression must explicitly specify optional argument values.
Expand Down
9 changes: 0 additions & 9 deletions stylecop.json

This file was deleted.

Loading
Loading