Testing with GUT & gdUnit4
Games are hard to test by hand: a bug in the save system or in the damage formula may only show up after twenty minutes of play. Automated tests run the same checks in seconds, after every change, and on a CI server. Godot has no built-in test framework, but two mature addons fill the gap: GUT (Godot Unit Test) and gdUnit4. This lesson shows what tests look like in both, how to run them headless, and what is worth testing in a game.
What to test in a game
Unit tests pay off for logic with rules: damage and healing, inventories, crafting recipes, save/load round trips, level parsing, state machine transitions, procedural generation with a seed, AI decisions. They pay off less for "does the jump feel good", which needs a human.
Two habits make game code testable:
- Keep rules in small classes or components (
Health,Inventory,SaveData) that can be created with.new()and checked without loading a whole level. That's also good architecture: see Field Notes: Scene Architecture. - Pass in what the code depends on (a
RandomNumberGeneratorwith a seed, a time value, an input direction) instead of reading globals, so a test can control it.
The idea in 60 lines
Both frameworks do the same basic thing: find methods whose names start with test_, run each one (letting it await frames or timers), and report the asserts that failed. Here is a tiny runner in the same style, testing a health component with a deliberate bug and a node that uses a timer:
extends Node
# frames: 30
# --- the code under test ---------------------------------------------
class Health extends Node:
signal died
var max_health := 3
var current := 3
func damage(amount: int) -> void:
if current == 0:
return
current = clampi(current - amount, 0, max_health)
if current == 0:
died.emit()
func heal(amount: int) -> void:
current = mini(current + amount, max_health + 1) # bug on purpose
class Blinker extends Node2D: # hides itself 0.1 s after start()
func start() -> void:
await get_tree().create_timer(0.1).timeout
visible = false
# --- a tiny GUT-style runner -------------------------------------------
var _failures: Array[String] = []
func assert_eq(got, expected, msg := "") -> void:
if got != expected:
_failures.append("expected %s, got %s%s" % [expected, got, " " + msg if msg else ""])
func _ready() -> void:
var passed := 0
var names: Array[String] = []
for m in get_method_list():
if m.name.begins_with("test_"):
names.append(m.name)
names.sort()
for test_name in names:
_failures.clear()
await call(test_name) # tests may await frames or timers
if _failures.is_empty():
passed += 1
print("PASS ", test_name)
else:
print("FAIL ", test_name, ": ", "; ".join(_failures))
print("%d/%d passed" % [passed, names.size()])
get_tree().quit()
# --- the tests -----------------------------------------------------------
func test_damage_reduces_health() -> void:
var h := Health.new()
h.damage(1)
assert_eq(h.current, 2)
h.free()
func test_died_emitted_once_at_zero() -> void:
var h := Health.new()
var count := [0]
h.died.connect(func(): count[0] += 1)
h.damage(5)
h.damage(1)
assert_eq(h.current, 0)
assert_eq(count[0], 1, "(died signals)")
h.free()
func test_heal_is_capped() -> void:
var h := Health.new()
h.damage(2)
h.heal(10)
assert_eq(h.current, h.max_health)
h.free()
func test_blinker_hides_after_timer() -> void:
var b := Blinker.new()
add_child(b)
b.start()
assert_eq(b.visible, true, "right after start")
await get_tree().create_timer(0.15).timeout
assert_eq(b.visible, false, "after 0.15 s")
b.queue_free()PASS test_blinker_hides_after_timer
PASS test_damage_reduces_health
PASS test_died_emitted_once_at_zero
FAIL test_heal_is_capped: expected 3, got 4
3/4 passed
The failing test found the bug: heal() caps at max_health + 1. Notice also that test_blinker_hides_after_timer really waited 0.15 seconds of game time for the timer: tests can drive the scene tree, not just plain functions. The real frameworks add what this model lacks: many assert types, doubles (fakes) and spies, parameterised tests, scene runners that simulate input, isolation between tests, an editor panel, and reports for CI.
GUT
GUT is the long-standing Godot test framework; GUT 9 is the line for Godot 4. Install it from the AssetLib, enable the plugin, and a GUT panel appears at the bottom of the editor. Tests are scripts that extend GutTest, usually in res://test/unit/ and named test_*.gd:
# res://test/unit/test_health.gd
extends GutTest
const Health = preload("res://components/health.gd")
var health: Health
func before_each() -> void:
health = Health.new()
add_child_autofree(health) # added to the tree, freed after the test
func test_damage_reduces_health() -> void:
health.damage(1)
assert_eq(health.current, health.max_health - 1, "one hit costs one point")
func test_died_is_emitted_at_zero() -> void:
watch_signals(health)
health.damage(99)
assert_signal_emitted(health, "died")
assert_signal_emit_count(health, "died", 1)
func test_heal_never_exceeds_max(p = use_parameters([1, 5, 100])) -> void:
health.damage(2)
health.heal(p)
assert_lte(health.current, health.max_health)
func test_flash_finishes() -> void:
var sprite: Sprite2D = add_child_autofree(preload("res://fx/flash_sprite.tscn").instantiate())
sprite.flash()
await wait_seconds(0.3)
assert_almost_eq(sprite.modulate.a, 1.0, 0.01)Highlights: before_each/after_each/before_all/after_all hooks; assert_eq, assert_ne, assert_true, assert_almost_eq, assert_has; signal watching; double() and stub() to replace dependencies; use_parameters() for parameterised tests; wait_seconds() and wait_frames() (or wait_physics_frames() in newer versions) for time-based behaviour. Run all tests from the panel, or from the command line:
godot --headless -s addons/gut/gut_cmdln.gd -gdir=res://test/unit -gexit-gexit quits when the tests finish, with a non-zero exit code if any failed, which is what CI needs. Settings can live in a .gutconfig.json file instead of flags.
gdUnit4
gdUnit4 is a newer framework with a fluent assert style, a test inspector panel, scene runners that simulate input, and support for C# tests too. Test suites extend GdUnitTestSuite; right-click a script in the editor and choose to create a test for it:
# res://test/health_test.gd
extends GdUnitTestSuite
const Health = preload("res://components/health.gd")
func test_damage_reduces_health() -> void:
var health: Health = auto_free(Health.new())
health.damage(1)
assert_int(health.current).is_equal(health.max_health - 1)
func test_inventory_contents() -> void:
var inventory := Inventory.new()
inventory.add("potion", 2)
assert_dict(inventory.items).contains_key_value("potion", 2)
assert_array(inventory.item_names()).contains_exactly(["potion"])
func test_player_jumps() -> void:
var runner := scene_runner("res://player/player.tscn")
runner.simulate_action_pressed("jump")
await runner.simulate_frames(5)
runner.simulate_action_released("jump")
assert_float(runner.get_property("velocity").y).is_less(0.0)auto_free() frees objects after the test, the assert_* family matches the value type (assert_int, assert_str, assert_vector, assert_signal, ...), and scene_runner() loads a scene and lets you press actions, move the mouse and step frames. It ships runtest.sh / runtest.cmd scripts for the command line (they need the GODOT_BIN environment variable pointing at your editor binary) and a GitHub Action for CI.
Which one?
| GUT | gdUnit4 | |
|---|---|---|
| Style | classic assert_eq(got, expected) |
fluent assert_int(x).is_equal(y) |
| Scene and input simulation | input sender, waits | scene_runner with actions, mouse, frames |
| C# tests | no | yes |
| History | the oldest, many tutorials | younger, very active |
Both are good. Pick one per project, write tests for the rules that have bitten you once, and run them on every push. Unity users will recognise the setup from Assembly Definitions & Tests.
Running tests in CI
A minimal GitHub Actions job downloads Godot, imports the project and runs GUT headless:
name: tests
on: [push, pull_request]
jobs:
gut:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Download Godot
run: |
curl -fsSL -o godot.zip "https://github.com/godotengine/godot/releases/download/4.7.2-stable/Godot_v4.7.2-stable_linux.x86_64.zip"
unzip -q godot.zip && mv Godot_v4.7.2-stable_linux.x86_64 godot
- name: Import assets
run: ./godot --headless --import
- name: Run tests
run: ./godot --headless -s addons/gut/gut_cmdln.gd -gdir=res://test/unit -gexitThe import step matters: a fresh checkout has no .godot/ cache, and scripts that preload() textures or scenes fail until assets are imported.
Test yourself
How do GUT and gdUnit4 find tests in a test script?
- Methods annotated with @test
- Methods whose names start with
test_ - Every method in the project
- Functions listed in project.godot
A test checks that a sprite fades in after 0.3 s. What should the test do?
- Call
OS.delay_msec(300) awaita framework wait (wait_seconds,simulate_frames) so the scene tree keeps running- Check immediately; tweens finish instantly in tests
- Tweens can't be tested
Why import assets (godot --headless --import) before running tests in CI?
- To export the game
- A fresh checkout has no
.godot/import cache, so preloaded resources would fail to load - To install GUT
- It makes tests run in parallel