Write a rendering code test
Write a graphics test where you render into a texture, then compare the texture to a reference image.
Follow these steps:
Create a script that includes the
NUnit.FrameworkandUnityEngine.TestTools.Graphicsnamespaces.Create a class with a method that has the
[Test]and[GraphicsTest]attributes. The method must accept aGraphicsTestCaseparameter, which the test framework automatically inputs into the test method.For example:
using System.Linq; using NUnit.Framework; using UnityEngine.TestTools.Graphics; using UnityEngine; class MyGraphicsTest { [Test, GraphicsTest] public void MyTestMethod(GraphicsTestCase testCase) { } }By default, Unity names reference images using the full parameterized test name. To customize this behavior, refer to Customize reference image naming.
Inside the method, render what you want to test. For example, the following code creates a 1 × 1 pixel red texture.
public void MyTestMethod(GraphicsTestCase testCase) { Texture2D texture = new Texture2D(1, 1, TextureFormat.RGB24, false); texture.SetPixel(0, 0, Color.red); texture.Apply(); }Compare the rendered texture to the reference image in the
testCaseusing theImageAssertAPI. For example:ImageAssert.AreEqual(testCase.ReferenceImage.Image, texture);
The test always fails the first time you run it because there's no reference image yet. For more information, refer to Run a graphics test for the first time.
Get a copy of a camera texture
To get a copy of the camera view or the back buffer as a texture, use the ImageCapture API.
To get a texture copy of the back buffer, use the ImageCapture.CaptureBackbuffer method. For example:
foreach (Texture2D frame in ImageCapture.CaptureBackbuffer(TextureFormat.RGB24))
{
ImageAssert.AreEqual(testCase.ReferenceImage.Image, frame);
}
To get a texture copy of a camera view, use the ImageCapture.CaptureFromCamera method. For example:
CameraCaptureSettings settings = new CameraCaptureSettings
{
targetWidth = 1920,
targetHeight = 1080,
useHDR = false,
msaaSamples = 1
};
Texture2D captured = ImageCapture.CaptureFromCamera(camera, TextureFormat.RGB24, settings).First();
To save the image, use the ImageCapture.SaveAsActual method. For example:
ImageCapture.SaveAsActual(captured, "MyTest_Actual");
Example
using NUnit.Framework;
using UnityEngine.TestTools.Graphics;
using UnityEngine;
class MyGraphicsTest
{
[Test, GraphicsTest]
public void RenderRedPixel(GraphicsTestCase testCase)
{
Texture2D texture = new Texture2D(1, 1, TextureFormat.RGB24, false);
texture.SetPixel(0, 0, Color.red);
texture.Apply();
ImageAssert.AreEqual(testCase.ReferenceImage.Image, texture);
}
}