AllocatingGCMemoryConstraint

class in UnityEngine.TestTools.Constraints

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

Description

An NUnit test constraint class to test whether a given block of code makes any GC allocations.

Use this class with NUnit's Assert.That() method to make assertions about the GC behaviour of your code. The constraint executes the delegate you provide, and checks if it caused any GC memory to be allocated. If any GC memory was allocated, the constraint passes; otherwise, the constraint fails.

Usually you negate this constraint to make sure that your delegate does not allocate any GC memory. This is easy to do using the Is class:

using NUnit.Framework;
using UnityEngine.TestTools.Constraints;
using Is = UnityEngine.TestTools.Constraints.Is;

public class MyTestClass { [Test] public void SettingAVariableDoesNotAllocate() { Assert.That(() => { int a = 0; a = 1; }, Is.Not.AllocatingGCMemory()); } }

Did you find this page useful? Please give it a rating: