Skip to content

Shared data-source instances are reused after disposal by tests registered later in the session #7204

Closed

Description

@thomhurst

What happens

When the last test holding a shared data-source instance (Shared = SharedType.Keyed, PerClass, PerAssembly or PerTestSession) completes, ObjectTracker.UntrackObject brings its reference count to zero and disposes it. TestDataContainer still caches the instance (ScopedDictionary.GetOrCreate), and it is only cleared by TestDataContainer.Reset() at the end of the session. A test that is registered later in the same session asks the container for the same key or scope, gets the disposed instance back, and gets a fresh reference count of 1 on it.

The usual way to register a test later is a dynamic test added at run time, after the original holders have completed.

Where

  • src/TUnit.Core/Tracking/ObjectTracker.cs, UntrackObject: disposes when the count reaches 0 and removes only the tracker entry.
  • src/TUnit.Core/TestDataContainer.cs, GetInstanceForKey / GetInstanceForClass / GetInstanceForAssembly / GetGlobalInstance: these return the cached instance whether or not it has been disposed.

How to reproduce

  1. Test A: [ClassDataSource<MyDisposable>(Shared = SharedType.Keyed, Key = "k")], where MyDisposable records IsDisposed.
  2. Test B: [DependsOn(nameof(A))] adds a dynamic test at run time whose class or method takes [ClassDataSource<MyDisposable>(Shared = SharedType.Keyed, Key = "k")].
  3. The dynamic test receives the instance that A's completion already disposed (IsDisposed == true).

This applies whatever A's outcome is (passed, failed, or skipped once #7191 merges). I found it by reading the code while reviewing #7191, where Greptile raised it for skipped tests. I have not run the repro yet.

Expected

A test registered after a shared instance has been disposed gets a new instance. For example, the container could drop its cache entry when the tracker disposes the object (ObjectTracker.OnDisposed), or the container could skip disposed entries.

Activity

  1. added
    bug
    on Oct 20, 2026
  2. added a commit that references this issue on Oct 30, 2026
    b3ea622
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions