godot-testing
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGodot 4 Testing
Godot 4 测试
A layered way to test GDScript games so most checks run headlessly in seconds, with no window and no human.
一种分层测试 GDScript 游戏的方法,让大多数检查都能在几秒内以无头方式完成,无需窗口,也无需人工介入。
When to Activate
适用场景
- Adding the first tests to a Godot project
- Writing or reviewing gdUnit4 or GUT suites
- Setting up a headless run for CI or a pre-commit check
- Asking "does this still run?" before handing a build to a playtester
- 为 Godot 项目添加首批测试
- 编写或审查 gdUnit4 或 GUT 测试套件
- 为 CI 或 pre-commit 检查设置无头运行
- 在把构建版本交给试玩人员之前询问“它现在还能运行吗?”
The Test Pyramid for Games
游戏测试金字塔
| Layer | What it checks | Needs a window? | Speed |
|---|---|---|---|
| 1. Logic tests | Pure rules in | No | Milliseconds |
| 2. Scene tests | A scene loads, nodes wire up, signals fire, a few frames run | No (usually) | Seconds |
| 3. Playtest | Feel, balance, fun | Yes, human | Minutes |
Write most tests at layer 1. That works only if game rules live outside Nodes. See .
godot-patterns| 层级 | 检查内容 | 需要窗口? | 速度 |
|---|---|---|---|
| 1. 逻辑测试 | | 否 | 毫秒级 |
| 2. 场景测试 | 场景能否加载、节点能否正确连接、 | 否(通常) | 秒级 |
| 3. 试玩 | 手感、平衡性、有趣程度 | 是,需要人工 | 分钟级 |
大多数测试应写在第 1 层。只有当游戏规则位于 Node 之外时,这才可行。参见 。
godot-patternsOption A: Zero-Dependency Check Scene
方案 A:零依赖检查场景
No addon needed. A scene with a script runs checks and sets the process exit code, so a shell or CI job can fail on it.
gdscript
undefined无需任何 addon。带脚本的场景会执行检查并设置进程退出码,因此 shell 或 CI 作业可据此判定失败。
gdscript
undefinedtests/verify_logic.gd, attached to the root Node of tests/verify_logic.tscn
tests/verify_logic.gd, attached to the root Node of tests/verify_logic.tscn
extends Node
extends Node
A tiny headless test runner. Run it with:
A tiny headless test runner. Run it with:
godot --headless --path . res://tests/verify_logic.tscn
godot --headless --path . res://tests/verify_logic.tscn
var _passed: int = 0
var _failed: int = 0
func _ready() -> void:
# Each test* function is one group of related checks.
_test_inventory_clamps_to_stack()
_test_health_never_negative()
print("%d passed, %d failed" % [_passed, _failed])
# A non-zero exit code is what tells CI the run failed.
get_tree().quit(1 if _failed > 0 else 0)var _passed: int = 0
var _failed: int = 0
func _ready() -> void:
# Each test* function is one group of related checks.
_test_inventory_clamps_to_stack()
_test_health_never_negative()
print("%d passed, %d failed" % [_passed, _failed])
# A non-zero exit code is what tells CI the run failed.
get_tree().quit(1 if _failed > 0 else 0)Records one assertion and prints a line only when it fails.
Records one assertion and prints a line only when it fails.
func _check(condition: bool, message: String) -> void:
if condition:
_passed += 1
else:
_failed += 1
push_error("FAIL: " + message) # push_error also shows in the debugger
func _test_inventory_clamps_to_stack() -> void:
var inv := Inventory.new()
var added: int = inv.add(&"wood", 150)
_check(added == Inventory.MAX_STACK, "add() clamps to MAX_STACK")
_check(inv.add(&"wood", 1) == 0, "a full stack accepts nothing more")
func _test_health_never_negative() -> void:
var health := Health.new() # a Node, so we free it ourselves at the end
health.damage(health.maximum + 50)
_check(health.current == 0, "health floors at zero")
health.free()
Why a scene and not `godot -s script.gd`: a scene run loads your autoloads normally, so code that references them works. Scripts started with `--script` run as the main loop, and autoload names can fail to resolve there.
Strengths: no install, tiny, easy to read. Limits: no test discovery, mocking, or nice reports. Move to Option B when this feels cramped.func _check(condition: bool, message: String) -> void:
if condition:
_passed += 1
else:
_failed += 1
push_error("FAIL: " + message) # push_error also shows in the debugger
func _test_inventory_clamps_to_stack() -> void:
var inv := Inventory.new()
var added: int = inv.add(&"wood", 150)
_check(added == Inventory.MAX_STACK, "add() clamps to MAX_STACK")
_check(inv.add(&"wood", 1) == 0, "a full stack accepts nothing more")
func _test_health_never_negative() -> void:
var health := Health.new() # a Node, so we free it ourselves at the end
health.damage(health.maximum + 50)
_check(health.current == 0, "health floors at zero")
health.free()
为什么使用场景而不是 `godot -s script.gd`:场景运行会像正常启动游戏一样加载 autoload,因此引用这些 autoload 的代码可以正常工作。通过 `--script` 启动的脚本会作为主循环运行,此时 autoload 名称可能无法解析。
优势:无需安装、体积小、易于阅读。局限:没有测试发现、mock 或清晰的报告。如果感觉不够用,就改用方案 B。Option B: gdUnit4
方案 B:gdUnit4
Embedded framework with fluent assertions, mocks, a scene runner, and a command-line runner. Install it from the Godot Asset Library or from its GitHub repository into , then enable it in Project Settings > Plugins.
addons/gdUnit4一个嵌入式框架,提供链式断言、mock、场景运行器和命令行运行器。可从 Godot Asset Library 或其 GitHub 仓库安装到 ,然后在 Project Settings > Plugins 中启用。
addons/gdUnit4A suite
测试套件
gdscript
undefinedgdscript
undefinedtests/test_inventory.gd
tests/test_inventory.gd
extends GdUnitTestSuite
extends GdUnitTestSuite
gdUnit4 finds methods whose names start with test_.
gdUnit4 finds methods whose names start with test_.
func test_add_clamps_to_stack() -> void:
var inv := Inventory.new()
var added: int = inv.add(&"wood", 150)
# Fluent assertion: assert_int(actual).is_equal(expected)
assert_int(added).is_equal(Inventory.MAX_STACK)
func test_add_emits_signal() -> void:
var inv := Inventory.new()
# monitor_signals lets us ask later whether a signal fired.
var monitor := monitor_signals(inv)
inv.add(&"wood", 5)
await assert_signal(inv).is_emitted("item_added", &"wood", 5)
undefinedfunc test_add_clamps_to_stack() -> void:
var inv := Inventory.new()
var added: int = inv.add(&"wood", 150)
# Fluent assertion: assert_int(actual).is_equal(expected)
assert_int(added).is_equal(Inventory.MAX_STACK)
func test_add_emits_signal() -> void:
var inv := Inventory.new()
# monitor_signals lets us ask later whether a signal fired.
var monitor := monitor_signals(inv)
inv.add(&"wood", 5)
await assert_signal(inv).is_emitted("item_added", &"wood", 5)
undefinedFixtures and cleanup
夹具与清理
- /
before()run once per suite.after()/before_test()run around each test.after_test() - Wrap anything you create in so gdUnit4 frees it after the test and you leak nothing.
auto_free(...) - Use when the node must be inside the tree.
add_child(auto_free(node))
- /
before()每个测试套件运行一次。after()/before_test()在每个测试前后运行。after_test() - 使用 包裹创建的每个对象,这样 gdUnit4 会在测试后释放它,避免资源泄漏。
auto_free(...) - 当节点必须位于场景树中时,使用 。
add_child(auto_free(node))
Scene runner (layer 2)
场景运行器(第 2 层)
gdscript
func test_player_moves_right() -> void:
# scene_runner loads the scene and lets us drive it like a player would.
var runner := scene_runner("res://scenes/main.tscn")
runner.simulate_action_pressed(&"move_right") # uses InputMap action names
await runner.simulate_frames(30) # let 30 frames pass
var player := runner.find_child("Player") as Node2D
assert_object(player).is_not_null()
assert_float(player.position.x).is_greater(0.0)gdscript
func test_player_moves_right() -> void:
# scene_runner loads the scene and lets us drive it like a player would.
var runner := scene_runner("res://scenes/main.tscn")
runner.simulate_action_pressed(&"move_right") # uses InputMap action names
await runner.simulate_frames(30) # let 30 frames pass
var player := runner.find_child("Player") as Node2D
assert_object(player).is_not_null()
assert_float(player.position.x).is_greater(0.0)Mocks
Mock
gdscript
func test_with_mock() -> void:
var mock_node := mock(Node) # a stand-in with the real method names
mock_node.get_name()
verify(mock_node).get_name() # asserts it was called exactly onceMock collaborators you do not own (a network client, a save system). Do not mock the class under test.
gdscript
func test_with_mock() -> void:
var mock_node := mock(Node) # a stand-in with the real method names
mock_node.get_name()
verify(mock_node).get_name() # asserts it was called exactly once可以 mock 你并不掌控的协作者,例如网络客户端或存档系统。不要 mock 被测类。
Running from the command line
从命令行运行
powershell
undefinedpowershell
undefinedRun every suite in tests/. Replace the path with your Godot executable if it is not on PATH.
Run every suite in tests/. Replace the path with your Godot executable if it is not on PATH.
godot --path . -s -d --remote-debug tcp://127.0.0.1:0 res://addons/gdUnit4/bin/GdUnitCmdTool.gd -a res://tests
- `-a <dir or file>` adds tests to run. `-i <suite>` ignores one. `-c` keeps going after a failure (the default is to stop at the first failure).
- gdUnit4's CI runner refuses to run in headless mode by default, because simulated input events do not work headless. If your suites do not depend on input, add `--ignoreHeadlessMode`. Suites that call `simulate_*` need a display or a virtual one (for example `xvfb` on Linux CI).
- The addon ships `runtest.sh` and a Windows equivalent that wrap this command. Check the version you installed.godot --path . -s -d --remote-debug tcp://127.0.0.1:0 res://addons/gdUnit4/bin/GdUnitCmdTool.gd -a res://tests
- `-a <dir or file>` 添加要运行的测试目录或文件。`-i <suite>` 忽略指定测试套件。`-c` 表示失败后继续运行,默认行为是在首次失败后停止。
- gdUnit4 的 CI 运行器默认拒绝以无头模式运行,因为模拟输入事件在无头模式下无效。如果测试套件不依赖输入,请添加 `--ignoreHeadlessMode`。调用 `simulate_*` 的测试套件需要显示环境或虚拟显示环境,例如 Linux CI 上的 `xvfb`。
- 该 addon 附带 `runtest.sh` 及其 Windows 对应脚本,它们封装了这条命令。请检查已安装的版本。Option C: GUT
方案 C:GUT
GUT (Godot Unit Test) is the other widely used addon.
gdscript
undefinedGUT(Godot Unit Test)是另一个广泛使用的 addon。
gdscript
undefinedtest/unit/test_health.gd
test/unit/test_health.gd
extends GutTest # GUT discovers methods starting with test_
func test_health_floors_at_zero() -> void:
var health := autofree(Health.new()) # autofree = freed after the test
health.damage(999)
assert_eq(health.current, 0, "health floors at zero")
```powershell
godot --headless --path . -s addons/gut/gut_cmdln.gd -gdir=res://test -gexit-gexitgut_cmdln.gd-ghextends GutTest # GUT discovers methods starting with test_
func test_health_floors_at_zero() -> void:
var health := autofree(Health.new()) # autofree = freed after the test
health.damage(999)
assert_eq(health.current, 0, "health floors at zero")
```powershell
godot --headless --path . -s addons/gut/gut_cmdln.gd -gdir=res://test -gexit-gexit-ghgut_cmdln.gdWhich Option?
该选择哪个方案?
| You are... | Pick |
|---|---|
| Starting out, small project | A (check scene), then graduate |
| Want scene-runner and mocks, GDScript and C# | B (gdUnit4) |
| Already using GUT | C, and do not mix two frameworks |
| 你的情况 | 选择 |
|---|---|
| 刚开始使用、项目规模较小 | A(检查场景),随后逐步迁移 |
| 需要场景运行器和 mock,并支持 GDScript 与 C# | B(gdUnit4) |
| 已经在使用 GUT | C,并且不要混用两个框架 |
Cheap Safety Checks (run these first)
低成本安全检查(优先运行这些)
powershell
undefinedpowershell
undefinedParse a script and exit: catches syntax errors without running the game.
Parse a script and exit: catches syntax errors without running the game.
Caveat: autoloads are not registered here, so scripts that use an autoload name
Caveat: autoloads are not registered here, so scripts that use an autoload name
report "Identifier not found" even though the game runs fine. The boot check below
report "Identifier not found" even though the game runs fine. The boot check below
is the authoritative compile test.
is the authoritative compile test.
godot --headless --path . --check-only --script res://scripts/player.gd
godot --headless --path . --check-only --script res://scripts/player.gd
Boot the project, load the main scene, and quit after a few frames. Catches load-time errors.
Boot the project, load the main scene, and quit after a few frames. Catches load-time errors.
godot --headless --path . --quit-after 5
godot --headless --path . --quit-after 5
Rebuild the import cache (needed on a fresh CI checkout before tests can load assets).
Rebuild the import cache (needed on a fresh CI checkout before tests can load assets).
godot --headless --path . --import
undefinedgodot --headless --path . --import
undefinedCI Sketch
CI 概览
yaml
undefinedyaml
undefined.github/workflows/tests.yml (outline only; pin versions you have tested)
.github/workflows/tests.yml (outline only; pin versions you have tested)
steps:
- uses: actions/checkout@v4
- name: Install Godot # use your preferred Godot setup action or a pinned download run: echo "install a pinned Godot build here"
- name: Import assets run: godot --headless --path . --import
- name: Run tests run: godot --headless --path . res://tests/verify_logic.tscn
Cache the `.godot/` import folder between runs to keep CI fast.steps:
- uses: actions/checkout@v4
- name: Install Godot # use your preferred Godot setup action or a pinned download run: echo "install a pinned Godot build here"
- name: Import assets run: godot --headless --path . --import
- name: Run tests run: godot --headless --path . res://tests/verify_logic.tscn
在多次运行之间缓存 `.godot/` 导入文件夹,以提升 CI 速度。Pitfalls
常见陷阱
| Pitfall | Fix |
|---|---|
| Tests pass locally, fail on CI | Missing import step. Run |
| Input simulation does nothing headless | Headless drops input events. Test the logic layer instead, or use a display. |
| Leaked nodes and orphan warnings | |
| Test depends on frame timing | |
| Tests share state through an autoload | Reset the autoload in |
| One giant test | One behavior per test, named for the behavior. |
| Randomness makes tests flaky | Seed a |
| 常见陷阱 | 修复方式 |
|---|---|
| 测试在本地通过,却在 CI 中失败 | 缺少导入步骤。先运行 |
| 无头模式下的输入模拟无效 | 无头模式会丢弃输入事件。改为测试逻辑层,或使用显示环境。 |
| 节点泄漏和 orphan 警告 | 使用 |
| 测试依赖帧时序 | 等待 |
| 测试通过 autoload 共享状态 | 在 |
| 一个巨型测试 | 每个测试只验证一种行为,并以该行为命名。 |
| 随机性导致测试不稳定 | 为 |
Related
相关内容
- Skill: for structuring code so layer 1 tests are possible
godot-patterns - Skill: for the red-green-refactor loop
tdd-workflow - Agent: for test-first guidance
tdd-guide - Agent: for review checklists
gdscript-reviewer
- Skill:,用于组织代码结构,使第 1 层测试成为可能
godot-patterns - Skill:,用于红-绿-重构循环
tdd-workflow - Agent:,提供测试优先的指导
tdd-guide - Agent:,提供审查检查清单
gdscript-reviewer