diff --git a/TUnit.Engine/Services/MetadataDependencyExpander.cs b/TUnit.Engine/Services/MetadataDependencyExpander.cs index 1267b2120d..fa9bdce9c3 100644 --- a/TUnit.Engine/Services/MetadataDependencyExpander.cs +++ b/TUnit.Engine/Services/MetadataDependencyExpander.cs @@ -148,6 +148,11 @@ public HashSet ExpandToIncludeDependencies( // Get candidate list based on dependency type for O(1) lookup IEnumerable candidates; + // When matching same-class dependencies by method name only, the candidate + // list spans all classes, so we must additionally filter by the current + // test's class type inside the loop below (avoids a per-iteration closure). + var filterByCurrentClassType = false; + if (dependency.ClassType != null && !string.IsNullOrEmpty(dependency.MethodName)) { // Specific class and method - use most specific index @@ -176,7 +181,8 @@ public HashSet ExpandToIncludeDependencies( // Same-class dependency by method name - look up by method name, then filter by class if (byMethodName.TryGetValue(dependency.MethodName!, out var list)) { - candidates = list.Where(m => m.TestClassType == current.TestClassType); + candidates = list; + filterByCurrentClassType = true; } else { @@ -191,6 +197,11 @@ public HashSet ExpandToIncludeDependencies( foreach (var candidateMetadata in candidates) { + if (filterByCurrentClassType && candidateMetadata.TestClassType != current.TestClassType) + { + continue; + } + if (dependency.Matches(candidateMetadata, current)) { if (result.Add(candidateMetadata))