Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feat(analyzer): add support for IAsyncInitializer.InitializeAsync met…
…hod in DisposableFieldPropertyAnalyzer
  • Loading branch information
thomhurst committed Oct 29, 2025
commit 900cf4c90c336a354e550f11f1f20618a5410c66
72 changes: 72 additions & 0 deletions TUnit.Analyzers.Tests/DisposableFieldPropertyAnalyzerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -582,4 +582,76 @@ public async Task RecordPaymentUsingMappedCommand(CancellationToken cancellation
"""
);
}

[Test]
public async Task New_Disposable_In_AsyncInitializer_Flags_Issue()
{
await Verifier
.VerifyAnalyzerAsync(
"""
using System;
using System.Net.Http;
using System.Threading.Tasks;
using TUnit.Core;
using TUnit.Core.Interfaces;

public class DisposableFieldTests : IAsyncInitializer
{
private HttpClient? {|#0:_httpClient|};

public Task InitializeAsync()
{
_httpClient = new HttpClient();
return Task.CompletedTask;
}

[Test]
public void Test1()
{
}
}
""",

Verifier.Diagnostic(Rules.Dispose_Member_In_Cleanup)
.WithLocation(0)
.WithArguments("_httpClient")
);
}

[Test]
public async Task New_Disposable_In_AsyncInitializer_No_Issue_When_Cleaned_Up()
{
await Verifier
.VerifyAnalyzerAsync(
"""
using System;
using System.Net.Http;
using System.Threading.Tasks;
using TUnit.Core;
using TUnit.Core.Interfaces;

public class DisposableFieldTests : IAsyncInitializer, IAsyncDisposable
{
private HttpClient? _httpClient;

public Task InitializeAsync()
{
_httpClient = new HttpClient();
return Task.CompletedTask;
}

public ValueTask DisposeAsync()
{
_httpClient?.Dispose();
return ValueTask.CompletedTask;
}

[Test]
public void Test1()
{
}
}
"""
);
}
}
15 changes: 14 additions & 1 deletion TUnit.Analyzers/DisposableFieldPropertyAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,20 @@ private static void CheckSetUps(SyntaxNodeAnalysisContext context, IMethodSymbol

var isHookMethod = methodSymbol.IsHookMethod(context.Compilation, out _, out var level, out _);

if (!isHookMethod && methodSymbol.MethodKind != MethodKind.Constructor)
// Check for IAsyncInitializer.InitializeAsync()
var isInitializeAsyncMethod = false;
if (methodSymbol is { Name: "InitializeAsync", Parameters.IsDefaultOrEmpty: true })
{
var asyncInitializer = context.Compilation.GetTypeByMetadataName("TUnit.Core.Interfaces.IAsyncInitializer");
if (asyncInitializer != null && methodSymbol.ContainingType.Interfaces.Any(x =>
SymbolEqualityComparer.Default.Equals(x, asyncInitializer)))
{
isInitializeAsyncMethod = true;
level = HookLevel.Test;
}
}

if (!isHookMethod && methodSymbol.MethodKind != MethodKind.Constructor && !isInitializeAsyncMethod)
{
return;
}
Expand Down