Search Unity

Resolved IPointerClickHandler test not working...

Discussion in 'Testing & Automation' started by Tazadar66, May 31, 2022.

  1. Tazadar66

    Tazadar66

    Joined:
    Aug 27, 2013
    Posts:
    57
    Hi everyone,
    I want to test my left click on a MonoBehaviour, it works in the Scene but not in the Unit test.
    Here is the code :

    Code (CSharp):
    1. public class PlayableElement : MonoBehaviour, IPointerClickHandler
    2.     {
    3.  
    4.         void IPointerClickHandler.OnPointerClick(PointerEventData eventData)
    5.         {
    6.             Debug.Log("Mouse down");
    7.         }
    8.     }
    And the non working test (it compiles but no Debug.Log so far...)
    The element is at the position 0 0.

    Code (CSharp):
    1.  
    2. public class PlayableElementTest : InputTestFixture
    3. {
    4. [UnityTest]
    5. public IEnumerator should_catch_click_correctly()
    6. {
    7. // Setup
    8. yield return EditorSceneManager.LoadSceneAsyncInPlayMode("Assets/Tests/Scenes/click.unity", new LoadSceneParameters(LoadSceneMode.Single));
    9.  
    10. var mouse = InputSystem.AddDevice<Mouse>();
    11. Move(mouse.position, Vector2.zero);
    12. Click(mouse.leftButton);
    13.  
    14. yield return new WaitForSeconds(1f);
    15. }
    16. }
    17.  
    Thanks for your help !
     
  2. Tazadar66

    Tazadar66

    Joined:
    Aug 27, 2013
    Posts:
    57
    OK I managed to make it work by using a script I found.
    Solution is here for your information just in case :

    Code (CSharp):
    1. public class PlayableElementTest : InputTestFixture
    2. {
    3.     Mouse _mouse;
    4.     public void ClickElement(GameObject element)
    5.     {
    6.         Camera camera = GameObject.FindObjectOfType<Camera>();
    7.         Vector3 screenPos = camera.WorldToScreenPoint(element.transform.position);
    8.         Set(_mouse.position, screenPos);
    9.         Click(_mouse.leftButton);
    10.     }
    11.  
    12.     public override void Setup()
    13.     {
    14.         base.Setup();
    15.         _mouse = InputSystem.AddDevice<Mouse>();
    16.     }
    17.  
    18.  
    19.     [UnityTest]
    20.     public IEnumerator should_catch_click_correctly()
    21.     {
    22.         // Setup
    23.         yield return EditorSceneManager.LoadSceneAsyncInPlayMode("Assets/Tests/Scenes/click.unity", new LoadSceneParameters(LoadSceneMode.Single));
    24.         // Act
    25.         PlayableElement pe = GameObject.FindObjectOfType<PlayableElement>();
    26.         ClickElement(pe.gameObject);
    27.         yield return null;
    28.     }
    29. }