Skip to content
Merged
Show file tree
Hide file tree
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
16 changes: 14 additions & 2 deletions docs/docs/writing-tests/mocking/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,15 @@ mock.Greet(Any()).Returns("Hello!");
mock.Greet("Alice").WasCalled();
```

The wrapper type is named after the interface with a `Mock` suffix (`IGreeter` → `IGreeterMock`) and lives in the interface's namespace. Declaring a variable, field or property as `Mock<IGreeter>` hides the wrapper. C# never applies user-defined conversions to interface types, so a `Mock<IGreeter>` needs `.Object` wherever an `IGreeter` is expected, and generic type inference, casts and `is`/`as` checks see `Mock<IGreeter>` rather than an `IGreeter`. The **TM011** suggestion flags locals, private fields and private properties declared as `Mock<T>` that only ever hold the wrapper, and its code fix changes the declaration to the wrapper type. Public, protected and internal members, and members of partial types split across files, are deliberately not flagged, because code the analyzer can't see could depend on their type:

```csharp
Mock<IGreeter> before = IGreeter.Mock(); // TM011: declare 'before' as 'IGreeterMock'
IGreeterMock after = IGreeter.Mock(); // after the fix
```

Run `dotnet format analyzers --diagnostics TM011 --severity info` to apply it to a whole project.

`T.Mock()` is the recommended syntax for all types — interfaces, abstract classes, and concrete classes. For interfaces it returns a typed wrapper; for classes it returns `Mock<T>`. Constructor arguments are supported as strongly-typed parameters:

```csharp
Expand All @@ -164,11 +173,14 @@ TUnit.Mocks requires C# 14 or later (`LangVersion` 14 or `preview`), because its

### Implicit Conversion

`Mock<T>` also supports implicit conversion to `T` — so `T.Mock()` works without `.Object`:
`Mock<T>` declares an implicit conversion to `T`, so a class mock works without `.Object`. C# never applies user-defined conversions to interface types, so for an interface mock either keep the wrapper type that `T.Mock()` returns, which implements the interface, or use `.Object`:

```csharp
var mock = IGreeter.Mock();
IGreeter greeter = mock; // implicit conversion
IGreeter greeter = mock; // the wrapper implements IGreeter

Mock<IGreeter> baseMock = mock;
IGreeter viaObject = baseMock.Object; // Mock<IGreeter> needs .Object
```

### Loose vs Strict Mode
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace TUnit.Mocks.Analyzers.CodeFixers;

/// <summary>
/// Changes a <c>Mock&lt;T&gt;</c> declaration to the generated mock type that <c>T.Mock()</c>
/// returns, e.g. <c>Mock&lt;IFoo&gt; mock = IFoo.Mock();</c> to <c>IFooMock mock = IFoo.Mock();</c>.
/// </summary>
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(PreferGeneratedMockTypeCodeFixProvider)), Shared]
public class PreferGeneratedMockTypeCodeFixProvider : CodeFixProvider
{
private const string Title = "Use the generated mock type";

// A const, so it is baked into this assembly rather than bound at runtime (see DiagnosticIds).
private const string MockTypeProperty = PreferGeneratedMockTypeAnalyzer.MockTypeProperty;

public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(DiagnosticIds.PreferGeneratedMockType);

public sealed override FixAllProvider GetFixAllProvider() =>
FixAllProvider.Create(static async (fixAllContext, document, diagnostics) =>
await FixDocumentAsync(document, diagnostics, fixAllContext.CancellationToken).ConfigureAwait(false));

public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
if (!diagnostic.Properties.TryGetValue(MockTypeProperty, out var mockType) || string.IsNullOrEmpty(mockType))
{
continue;
}

context.RegisterCodeFix(
CodeAction.Create(
title: $"Declare as '{mockType}'",
createChangedDocument: c => FixDocumentAsync(context.Document, ImmutableArray.Create(diagnostic), c),
equivalenceKey: Title),
diagnostic);
}

return Task.CompletedTask;
}

private static async Task<Document> FixDocumentAsync(
Document document,
ImmutableArray<Diagnostic> diagnostics,
CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
if (root is null)
{
return document;
}

var replacements = new Dictionary<TypeSyntax, TypeSyntax>();

foreach (var diagnostic in diagnostics)
{
if (!diagnostic.Properties.TryGetValue(MockTypeProperty, out var mockType)
|| string.IsNullOrEmpty(mockType)
|| root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true) is not TypeSyntax declaredType)
{
continue;
}

// Keep a nullable annotation: Mock<IFoo>? -> IFooMock?
var target = declaredType is NullableTypeSyntax nullable ? nullable.ElementType : declaredType;
replacements[target] = SyntaxFactory.ParseTypeName(mockType!).WithTriviaFrom(target);
}

if (replacements.Count == 0)
{
return document;
}

var newRoot = root.ReplaceNodes(replacements.Keys, (original, _) => replacements[original]);
return document.WithSyntaxRoot(newRoot);
}
}
1 change: 1 addition & 0 deletions src/TUnit.Mocks.Analyzers/DiagnosticIds.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ public static class DiagnosticIds
public const string CannotMockInterfaceWithInaccessibleMember = "TM007";
// TM008 and TM009 are reported by TUnit.Mocks.SourceGenerator (see its Diagnostics.cs).
public const string PreferStaticMockSyntax = "TM010";
public const string PreferGeneratedMockType = "TM011";
}
Loading
Loading