You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity单元测试中如何使用新InputSystem选中InputField?

Unity新InputSystem UI Play Mode测试问题

我正尝试为UI集成Play Mode单元测试,发现新InputSystem支持自动化输入测试。查阅官方文档及GitHub仓库中的示例后,仍不清楚如何搭建测试。

我尝试编写了一个简单的UnityTest方法,模拟虚拟鼠标移动到InputField上方并点击:

[UnityTest]
public IEnumerator InputSystem_MovePointerAndClickInputField_InputFieldIsSelected()
{
    // Arrange
    var inputField = GameObject.FindFirstObjectByType<TMP_InputField>();
    var inputFieldRect = inputField.GetComponent<RectTransform>();
    var fieldScreenPosition = RectTransformUtility.WorldToScreenPoint(Camera.main, inputFieldRect.position);

    var mouse = InputSystem.AddDevice<Mouse>();

    // Act
    Set(mouse.position, fieldScreenPosition);
    Press(mouse.leftButton);
    Release(mouse.leftButton);
    yield return null;

    // Assert
    Assert.That(inputField.isFocused, Is.True);
}

但断言结果始终为False,输入框并未被选中。


编辑后的解决方案

在他人建议下,我放弃模拟用户输入,改为直接调用TMP_InputField.Select()方法激活输入框,再通过TMP_InputField.ProcessEvent()输入文本:

[UnityTest]
public IEnumerator InputSystem_MovePointerAndClickInputField_InputFieldIsSelected()
{
    // Arrange
    var inputField = GameObject.FindFirstObjectByType<TMP_InputField>();
    var inputFieldRect = inputField.GetComponent<RectTransform>();

    // Act
    inputField.Select();
    yield return null;
    Assert.That(inputField.isFocused, Is.True);

    string textInput = "I typed this text";
    foreach (char c in textInput)
    {
        inputField.ProcessEvent(Event.KeyboardEvent($"{c}"));
        inputField.ForceLabelUpdate();
        yield return new WaitForSeconds(.2f);
    }

    // Assert
    Assert.That(inputField.text, Is.EqualTo(textInput));
}

内容的提问来源于stack exchange,提问作者Miky_Santos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 01:03:31