Skip to main content
3 of 5
Code formatting
DMGregory
  • 140.8k
  • 23
  • 257
  • 401

Testing Message-Based Events using Unity's New Input System and InputTestFixture, getting unhelpful error

My player has an Action in the Input System Move, that takes a Vector2 and moves the player based on that input. Straight-forward. I'm using the "Send Messages" behavior on my Player's PlayerInput component.

For the life of me, I can't figure out how to test if OnMove is being called effectively. Here's my most recent attempt, I've tried instantiating the player piecewise from a new game object, loading the player as a prefab, finding the player in the scene, doing any and all of these things in the test and in a setup test function, and I've gotten nowhere.

Test

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Core;
using FluentAssertions;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;

namespace Tests.PlayMode {
    public class PlayerTests {
        public class Physics {...}

        public class Animations {...}

        public class Movement : InputTestFixture {

            [UnityTest]
            public IEnumerator Player_Should_Be_Able_To_Move() {
                SceneManager.LoadScene("TestScene");
                yield return new WaitForSeconds(0.1f);
                
                InputSystem.RegisterLayout<Keyboard>();
                var keyboard = InputSystem.AddDevice<Keyboard>();

                var playerPrefabObject = Resources.Load("Player");
                var playerGameObject = (GameObject)Object.Instantiate(playerPrefabObject);
                var player = playerGameObject.GetComponent<Player>();
                
                yield return new WaitForSeconds(0.5f);
                player.Rigidbody.velocity.x.Should().Be(0);
                
                Press(keyboard.dKey);
                yield return new WaitForSeconds(0.1f);
                Debug.Log(player.MoveDir);
                Debug.Log(player.Rigidbody.velocity);
                player.Rigidbody.velocity.x.Should().BePositive();
                
                Release(keyboard.dKey);
            }
        }
    }
}

Player

using UnityEngine;
using UnityEngine.InputSystem;

namespace Core {
    public class Player : MonoBehaviour {
        public Rigidbody2D Rigidbody { get; private set; }
        public CapsuleCollider2D Collider { get; private set; }
        public Vector2 MoveDir { get; private set; }
    
        private void Start() {
            Rigidbody = GetComponent<Rigidbody2D>();
            Collider = GetComponent<CapsuleCollider2D>();
        }

        public void OnMove(InputValue value) {
            Debug.Log("OnMove called");
            MoveDir = value.Get<Vector2>();
            Rigidbody.velocity = MoveDir * 10f;
        }
    }
}
JShoe
  • 75
  • 8