docs.unity3d.com
Search Results for

    Show / Hide Table of Contents

    Clean up objects after tests

    To clean up objects after tests, call AddTestComponent<CleanupUtil>() to add a CleanupUtil component to the test fixture. The CleanupUtil component helps you dispose of or destroy objects at the end of each test, ensuring that your tests don't leave behind unwanted state or resources.

    The following example shows how to use the CleanupUtil:

    public class CleanupUtilExampleClass : UITestFixture
    {
        CleanupUtil m_CleanupUtil;
    
        [OneTimeSetUp]
        public void OneTimeSetUp()
        {
            // Add the test component and keep its reference
            // to add objects to be destroyed later.
            m_CleanupUtil = AddTestComponent<CleanupUtil>();
        }
    
        [Test]
        public void CleanupUtilExample()
        {
            // Create a game object to use in the test.
            GameObject go = new GameObject("GameObjectToDispose");
    
            // Add the game object to be destroyed after the test.
            // GameObject is of type Object so we use the AddDestructible method.
            m_CleanupUtil.AddDestructible(go);
    
            // Create another item.
            DisposableTestItem item = new DisposableTestItem();
    
            // Add the item to be disposed after the test.
            // DisposableTestItem implements the IDisposable interface
            // so we use the AddDisposable method.
            m_CleanupUtil.AddDisposable(item);
    
            // Test steps.
            // ...
        }
    }
    
    internal class DisposableTestItem : IDisposable
    {
        public void Dispose()
        {
            // Dispose steps.
        }
    }
    

    Additional resources

    • UITestComponent
    • AddTestComponent<T>
    In This Article
    Back to top
    Copyright © 2025 Unity Technologies — Trademarks and terms of use
    • Legal
    • Privacy Policy
    • Cookie Policy
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)