I am trying to make automated UI tests in Unity. Below is my test script. It is supposed to simulate a mouse click at a specified location, wait until the character moves there, then record the character's location (later, I will be adding an assertion that the character is within a certain distance from the clicked location). It runs without errors, but does not move my character like it should when I run the test. In play mode, my character moves as expected when the mouse is clicked somewhere on the map.
[UnityTest]
public IEnumerator TestCharacterMovement()
{
//UnityEngine.Debug.Log(Time.timeScale); //=1
mouse = InputSystem.AddDevice<Mouse>();
SceneManager.LoadScene("charactercontroller");
yield return new WaitForSeconds(1f);
character = GameObject.Find("Copy_of_JPEG_Page_22-removebg-preview");
yield return new WaitForSeconds(1f);
Assert.IsTrue(character != null);
//tried 1, 10, and 100 here for difference in x
Vector3 clickPosition = new Vector3(character.transform.position.x + 1f, character.transform.position.y, character.transform.position.z);
Camera camera = GameObject.Find("Main Camera").GetComponent<Camera>();
Vector3 screenpos = camera.WorldToScreenPoint(clickPosition);
Set(mouse.position, screenpos);
yield return new WaitForSeconds(1f);
Click(mouse.leftButton);
UnityEngine.Debug.Log(mouse.position.x.ReadValue());
UnityEngine.Debug.Log(mouse.position.y.ReadValue());
yield return new WaitForSeconds(2f);
yield return null;
}
Below is my movement script for the character. In play mode, "A" gets printed continuously, "B" gets printed when I click, and "tab" gets printed when I press the tab key. As expected.
When I run my test however, only A prints. Mouse clicks and pressing the tab key are both not registered. What am I doing wrong?
namespace MovementScript
{
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
public class movement : MonoBehaviour
{
public float speed = 5f;
public Vector3 target;
void Start()
{
target = transform.position;
}
void Update()
{
UnityEngine.Debug.Log("A");
if (Input.GetMouseButtonDown(0))
{
target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
UnityEngine.Debug.Log("B");
target.z = transform.position.z;
target.y = transform.position.y;
}
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
if (target.x > transform.position.x)
{
transform.rotation = Quaternion.Euler(new Vector3(0, 180, 0));
}
else if (target.x < transform.position.x)
{
transform.rotation = Quaternion.Euler(new Vector3(0, 0, 0));
}
if (Input.GetKeyDown(KeyCode.Tab))
{
UnityEngine.Debug.Log("tab");
}
}
}
}