diff --git a/TUnit.Engine/Extensions/TestContextExtensions.cs b/TUnit.Engine/Extensions/TestContextExtensions.cs index 27c00913fa..381cfd2cf2 100644 --- a/TUnit.Engine/Extensions/TestContextExtensions.cs +++ b/TUnit.Engine/Extensions/TestContextExtensions.cs @@ -148,11 +148,10 @@ private static T[] SortAndFilter(List? receivers) where T : class, IEventR } // Sort by Order - receivers.Sort((a, b) => a.Order.CompareTo(b.Order)); + receivers.Sort(static (a, b) => a.Order.CompareTo(b.Order)); - // Apply scoped attribute filtering and return as array - var filtered = ScopedAttributeFilter.FilterScopedAttributes(receivers); - return filtered.ToArray(); + // Apply scoped attribute filtering - FilterScopedAttributes already returns T[] + return ScopedAttributeFilter.FilterScopedAttributes(receivers); } public static IEnumerable GetEligibleEventObjects(this TestContext testContext) diff --git a/TUnit.Engine/Services/EventReceiverOrchestrator.cs b/TUnit.Engine/Services/EventReceiverOrchestrator.cs index 050d4e4ec1..86da7d018a 100644 --- a/TUnit.Engine/Services/EventReceiverOrchestrator.cs +++ b/TUnit.Engine/Services/EventReceiverOrchestrator.cs @@ -287,13 +287,17 @@ private static async Task InvokeTestDiscoveryEventReceiversCoreAsync(ITestDiscov public async ValueTask InvokeHookRegistrationEventReceiversAsync(HookRegisteredContext hookContext, CancellationToken cancellationToken) { - // Filter scoped attributes to ensure only the highest priority one of each type is invoked + // Pre-sort by Order before filtering so that FilterScopedAttributes (which uses TryAdd + // and keeps the first encountered item per ScopeType) retains the lowest-Order attribute. + // After filtering, sort the result in-place for final invocation order. var filteredReceivers = ScopedAttributeFilter.FilterScopedAttributes( hookContext.HookMethod.Attributes .OfType() - .OrderBy(static r => r.Order)); + .OrderBy(static x => x.Order)); - foreach (var receiver in filteredReceivers.OrderBy(static r => r.Order)) + Array.Sort(filteredReceivers, static (a, b) => a.Order.CompareTo(b.Order)); + + foreach (var receiver in filteredReceivers) { await receiver.OnHookRegistered(hookContext); }