Skip to content

Instantly share code, notes, and snippets.

@abeldantas
Last active October 9, 2023 08:15
Show Gist options
  • Save abeldantas/8b56792d294b2e163c52a1d5c00954d0 to your computer and use it in GitHub Desktop.
Save abeldantas/8b56792d294b2e163c52a1d5c00954d0 to your computer and use it in GitHub Desktop.
Quickstart Unity C# test template. Not perfect, but gets you testing now.
using System.Collections;
using System.Threading.Tasks;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
// Namespace should mirror the implementation namespace with a '.Tests' suffix.
// If the implementation is under 'MyCompany.FeatureScope', then tests should be 'MyCompany.Tests.FeatureScope'.
namespace MyCompany.Tests.FeatureScope
{
// Class name should be the same as the implementation class with a 'Tests' suffix.
// If you have a class named 'Feature', then the test class should be 'FeatureTests'.
public class FeatureTests
{
private GameObject testObject;
[SetUp]
public void SetUp()
{
// Setup code for each test
var go = new GameObject("TestObject");
testObject = go;
}
[TearDown]
public void TearDown()
{
// Cleanup after each test method
Object.DestroyImmediate(testObject);
}
// Method names should mirror the corresponding method names in the implementation,
// optionally with an additional descriptor. For example, if testing a method 'Create' in the implementation,
// a good test name might be 'Create_Succeeds'.
[Test]
public void CreateGameObject_EditMode()
{
Assert.AreEqual("TestObject", testObject.name);
}
[UnityTest]
public IEnumerator CreateGameObject_PlayMode()
{
yield return null;
Assert.AreEqual("TestObject", testObject.name);
}
// Example integration test
[UnityTest]
public IEnumerator ExampleIntegrationTest_Success()
{
yield return null; // Wait one frame
// Simulate some asynchronous action, like making a network request
// You would replace this with your actual logic
yield return new WaitForSeconds(1);
// Assert: Replace with your actual assertions
Assert.IsTrue(true);
}
// Parameterized Tests
[TestCase(1, 1, 2)]
[TestCase(2, 2, 4)]
public void AddNumbers(int a, int b, int expected)
{
Assert.AreEqual(expected, a + b);
}
// Async Test
[Test]
public async Task ExampleAsyncTest()
{
await SomeAsyncMethod();
Assert.IsTrue(true);
}
private async Task SomeAsyncMethod()
{
await Task.Delay(1000);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment