Write a scene test
Write a graphics test that compares a scene to a reference image.
To write a scene test, follow these steps:
Create a script that includes the
NUnit.Framework,UnityEngine.TestTools.Graphics, andUnityEngine.SceneManagementnamespaces.Create a class with a test method that accepts a
SceneGraphicsTestCaseparameter. The test framework automatically inputs the test case into the test method.For example:
using NUnit.Framework; using UnityEngine.TestTools.Graphics; using UnityEngine; using UnityEngine.SceneManagement; class MySceneGraphicsTest { // The test method must accept a SceneGraphicsTestCase parameter public IEnumerator MySceneTest(SceneGraphicsTestCase testCase) { } }Add the
[UnityTest]attribute to the test method, and aSceneGraphicsTestattribute with the path to the folder that contains the scenes you want to test. For example:[UnityTest, SceneGraphicsTest("Assets/Scenes")] public IEnumerator MySceneTest(SceneGraphicsTestCase testCase) { // Test code here }The scene path parameter accepts single
.unityscene files, asset paths, directory paths, or regex patterns. For example,Assets/Scenes/[0-9]+.Unity generates a
testCasefor each scene in the folder.Load the scene using
SceneManager.LoadScenewith theScenePathproperty of thetestCase. For example:SceneManager.LoadScene(testCase.ScenePath, LoadSceneMode.Single); // Wait a frame for rendering to complete yield return null;Compare the camera view to the reference image in the
testCaseusing theImageAssertAPI. For example:// Get the camera view Camera camera = Object.FindFirstObjectByType<Camera>(); // Check the camera view matches the reference image ImageAssert.AreEqual(testCase.ReferenceImage.Image, camera);
The test always fails the first time you run it because there's no reference image yet. For more information, refer to Run the test for the first time.
Exclude a scene from testing
To exclude a scene in the Scenes folder, use [IgnoreGraphicsTest].
Note: You can't exclude a scene by removing it from a build profile. The Unity Test Framework package doesn't use build profiles to find scenes.
Example
using NUnit.Framework;
using UnityEngine.TestTools.Graphics;
using UnityEngine;
using UnityEngine.SceneManagement;
class MySceneGraphicsTest
{
[UnityTest, SceneGraphicsTest("Assets/Scenes")]
public IEnumerator RenderScene(SceneGraphicsTestCase testCase)
{
SceneManager.LoadScene(testCase.ScenePath, LoadSceneMode.Single);
yield return null;
Camera camera = Object.FindFirstObjectByType<Camera>();
ImageAssert.AreEqual(testCase.ReferenceImage.Image, camera);
}
}