docs.unity3d.com
Search Results for

    Show / Hide Table of Contents

    Simulate context menu actions

    To validate and simulate context menu actions in your tests, use the AddTestComponent<T> method to create a ContextMenuSimulator test component. The ContextMenuSimulator doesn't spawn context menus, so you must activate them in the test.

    The following examples show how to use the ContextMenuSimulator to validate and interact with a context menu:

    public class ContextMenuSimulatorExampleClass : UITestFixture
    {
        ContextMenuSimulator m_ContextMenuSimulator;
    
        [OneTimeSetUp]
        public void OneTimeSetUp()
        {
            // Add the test component and keep its reference
            // to add styles to elements later.
            m_ContextMenuSimulator = AddTestComponent<ContextMenuSimulator>();
        }
    
        [Test]
        public void ContextMenuSimulatorExample()
        {
            Label label = rootVisualElement.Q<Label>("MyLabel");
    
            Vector2 clickLocation = new Vector2(label.worldBound.x, label.worldBound.yMin);
    
            // Select some text from the label.
            simulate.DoubleClick(clickLocation);
            simulate.FrameUpdate();
    
            // Right-click over the text to activate the context menu.
            simulate.Click(clickLocation,
                MouseButton.RightMouse);
            simulate.FrameUpdate();
    
            // Check that the menu is displayed.
            Assert.That(m_ContextMenuSimulator.menuIsDisplayed,
                Is.True, "ContextMenu was not displayed.");
    
            // Check that the menu contains the item we want to select.
            m_ContextMenuSimulator.AssertContainsAction("Copy");
    
            // Execute the Copy menu action.
            m_ContextMenuSimulator.SimulateMenuSelection("Copy");
    
            // Fetch and focus the textField's textElement.
            var textField = rootVisualElement.Q<TextField>("MyTextField");
            var textElement = textField.Q<TextElement>();
            Assume.That(textField, Is.Not.Null);
            textField.Focus();
            Assert.That(textField.value, Is.Empty);
    
            // Paste the text in textField.
            simulate.ExecuteCommand("Paste");
            simulate.FrameUpdate();
    
            Assert.That(textField.value, Is.Not.Empty);
        }
    
        [SetUp]
        public void SetUp()
        {
            VisualTreeAsset uxml = Resources.Load<VisualTreeAsset>("UITestFrameworkDocSample");
            uxml.CloneTree(rootVisualElement);
    
            simulate.FrameUpdate();
        }
    }
    

    Additional resources

    • Simulate popup menu actions
    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)