Run tests from editor script

Is there a way i can access the Unity Test Runner from editor scripts?

I want to add a button to the unity editor that runs a predifined set of tests. Its behaviour should be the same as selecting the corresponding tests in the Test Runner window and pressing run.

thanks,

MH

Hey. It is currently not possible, but we will be releasing a new API that will make it possible to do that. We hope to have that ready in the summer.

Is this API available already?

Yes, if you are on Unity 2019.2 or higher, you can install the “Test framework” package that includes this functionality.

Here’s an example taken from my UnityTestExtensions library, that adds menu items that run your tests.
You could also call these static methods from any editor script to achieve the same result:

using UnityEditor;
using UnityEditor.TestTools.TestRunner.Api;
using UnityEngine;

namespace UnityTestExtensions
{
    public static class TestMenuItems
    {
        /// <summary>
        /// Runs all edit mode tests.
        /// </summary>
        [MenuItem("Window/General/Test Extensions/Run Edit Mode Tests")]
        public static void RunEditModeTests()
        {
            RunTests(TestMode.EditMode);
        }
      
        /// <summary>
        /// Runs all play mode tests.
        /// </summary>
        [MenuItem("Window/General/Test Extensions/Run Play Mode Tests")]
        public static void RunPlayModeTests()
        {
            RunTests(TestMode.PlayMode);
        }

        private static void RunTests(TestMode testModeToRun)
        {
            var testRunnerApi = ScriptableObject.CreateInstance<TestRunnerApi>();
            var filter = new Filter()
            {
                testMode = testModeToRun
            };
          
            testRunnerApi.Execute(new ExecutionSettings(filter));
        }
    }
}
6 Likes

Hey @Warnecke , did you finally released that new API?

Yep, see here: TestRunnerApi | Test Framework | 1.1.33