godot-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Godot Testing

Godot 测试

This skill covers test-driven development (TDD) for Godot 4.3+ projects using GUT (Godot Unit Testing) and gdUnit4. It includes framework selection, full RED-GREEN-REFACTOR examples, test structure, running tests in CI, and common testing patterns.
Related skills: godot-code-review for review checklists, dependency-injection for test-friendly architecture, export-pipeline for CI/CD test automation.
本 skill 介绍如何在 Godot 4.3+ 项目中使用 GUT(Godot Unit Testing)和 gdUnit4 进行测试驱动开发(TDD)。内容包括框架选择、完整的 RED-GREEN-REFACTOR 示例、测试结构、在 CI 中运行测试,以及常见的测试模式。
相关 skill: godot-code-review 提供审查清单,dependency-injection 介绍便于测试的架构,export-pipeline 介绍 CI/CD 测试自动化。

Framework Selection

框架选择

FeatureGUTgdUnit4
LanguageGDScript-first, limited C#GDScript + C# (first-class)
InstallAssetLib or git submoduleAssetLib or git submodule
Editor integrationBuilt-in GUT panelBuilt-in inspector + panel
Mocking
double()
/
stub()
API
mock()
/
spy()
API
Scene testing
add_child_autofree()
auto_free()
+ scene runner
CI support
gut_cmdln.gd
CLI script
runtest.sh
/
GdUnitCmdTool.gd
C# supportMinimal (GDScript wrappers only)Native C# assertions + lifecycle
MaturityEstablished (Godot 3 + 4)Godot 4 focused, actively updated
Best forPure GDScript projectsMixed GDScript/C# or C#-only
Rule of thumb: Use GUT for GDScript-only projects. Use gdUnit4 for C# projects or when you need first-class C# support and scene runner utilities.

特性GUTgdUnit4
语言以 GDScript 为主,仅有限支持 C#GDScript + C#(一等支持)
安装AssetLib 或 git submoduleAssetLib 或 git submodule
编辑器集成内置 GUT panel内置 inspector + panel
Mock
double()
/
stub()
API
mock()
/
spy()
API
场景测试
add_child_autofree()
auto_free()
+ scene runner
CI 支持
gut_cmdln.gd
CLI 脚本
runtest.sh
/
GdUnitCmdTool.gd
C# 支持最低限度支持(仅 GDScript 包装器)原生 C# 断言 + 生命周期
成熟度成熟(支持 Godot 3 + 4)专注 Godot 4,持续更新
最适合纯 GDScript 项目混合 GDScript/C# 或仅 C# 项目
经验法则: 对于仅使用 GDScript 的项目,选择 GUT。对于 C# 项目,或需要一等 C# 支持和 scene runner 工具的项目,选择 gdUnit4。

TDD Workflow: RED-GREEN-REFACTOR

TDD 工作流:RED-GREEN-REFACTOR

The standard Test-Driven Development cycle: write a failing test (RED), write minimal code to pass (GREEN), then refactor without breaking the test. Each step has its own discipline — don't skip RED (you'll write tests that pass trivially), and don't skip REFACTOR (technical debt compounds).
See references/tdd-workflow.md for a worked GDScript + C# example walking through all three steps on a HealthComponent.

标准的测试驱动开发循环:先编写一个失败的测试(RED),再编写最少量的代码使测试通过(GREEN),最后在不破坏测试的前提下重构。每个步骤都有其对应的实践要求——不要跳过 RED(否则测试会毫无意义地直接通过),也不要跳过 REFACTOR(否则技术债务会不断累积)。
有关 references/tdd-workflow.md 的完整 GDScript + C# 示例,请参阅其中对 HealthComponent 三个步骤的详细演示。

Test Directory Structure

测试目录结构

res://
├── .gutconfig.json                       # GUT default config file (optional)
├── src/
│   └── components/
│       ├── health_component.gd
│       └── HealthComponent.cs
└── tests/
    ├── unit/
    │   ├── test_health_component.gd      # GUT: test_ prefix (default -gprefix)
    │   └── HealthComponentTest.cs        # gdUnit4 C#: [TestSuite] attribute
    └── integration/
        ├── test_player_scene.gd
        └── PlayerSceneTest.cs
res://
├── .gutconfig.json                       # GUT default config file (optional)
├── src/
│   └── components/
│       ├── health_component.gd
│       └── HealthComponent.cs
└── tests/
    ├── unit/
    │   ├── test_health_component.gd      # GUT: test_ prefix (default -gprefix)
    │   └── HealthComponentTest.cs        # gdUnit4 C#: [TestSuite] attribute
    └── integration/
        ├── test_player_scene.gd
        └── PlayerSceneTest.cs

Naming conventions

命名约定

FrameworkGDScript fileC# fileTest method prefix/attribute
GUT
test_*.gd
N/A
func test_*()
gdUnit4any name (
*_test.gd
when generated)
*Test.cs
func test_*()
/
[TestCase]

框架GDScript 文件C# 文件测试方法前缀或属性
GUT
test_*.gd
不适用
func test_*()
gdUnit4任意名称(生成时为
*_test.gd
)
*Test.cs
func test_*()
/
[TestCase]

Running Tests

运行测试

Both frameworks ship a CLI runner. GUT:
addons/gut/gut_cmdln.gd
invoked via
godot --headless --path . -s addons/gut/gut_cmdln.gd -gexit
(without
-gexit
the run never quits). gdUnit4:
addons/gdUnit4/runtest.sh -a res://tests
(wraps
bin/GdUnitCmdTool.gd
; under
--headless
it also needs
--ignoreHeadlessMode
), or the editor's GdUnit dock. CI: tag-triggered or PR-triggered GitHub Action that installs Godot, runs the suite, exits non-zero on failure.
See references/running-tests.md for full GUT and gdUnit4 CLI invocations + a copy-pasteable GitHub Actions workflow.

两个框架都提供 CLI 运行器。GUT: 通过
godot --headless --path . -s addons/gut/gut_cmdln.gd -gexit
调用
addons/gut/gut_cmdln.gd
(不使用
-gexit
时,运行永远不会退出)。gdUnit4: 使用
addons/gdUnit4/runtest.sh -a res://tests
(它封装了
bin/GdUnitCmdTool.gd
;在
--headless
模式下还需要
--ignoreHeadlessMode
),也可以使用编辑器中的 GdUnit dock。CI:可使用由 tag 或 PR 触发的 GitHub Action,安装 Godot、运行测试套件,并在失败时以非零状态退出。
有关完整的 GUT 和 gdUnit4 CLI 调用方式,以及可直接复制使用的 GitHub Actions 工作流,请参阅 references/running-tests.md。

Testing Patterns

测试模式

Four common patterns: scenes with nodes (instantiate via
add_child
in
before_each
, free in
after_each
), signal testing (assert that emitting works and connect-then-emit fires), mocking/doubling (gdUnit4
mock()
in GDScript; in C#, hand-rolled fakes via
@export
injection), async (await yields, signals, frames in tests).
See references/testing-patterns.md for full code on each pattern (GDScript + C# where applicable).

常见的四种模式:包含节点的场景(在
before_each
中通过
add_child
实例化,在
after_each
中释放)、信号测试(断言信号能够发出,并验证连接后触发信号时会执行对应逻辑)、Mock/Double(GDScript 中使用 gdUnit4 的
mock()
;在 C# 中通过
@export
注入自行实现的 fake)、异步测试(在测试中 await yield、信号和帧)。
有关每种模式的完整代码(GDScript + C#,如适用),请参阅 references/testing-patterns.md。

Common Assertions

常用断言

GUT assertions

GUT 断言

AssertionDescription
assert_eq(actual, expected)
Equality
assert_ne(actual, expected)
Not equal
assert_true(value)
Is truthy
assert_false(value)
Is falsy
assert_null(value)
Is null
assert_not_null(value)
Is not null
assert_gt(actual, expected)
Greater than
assert_lt(actual, expected)
Less than
assert_gte(actual, expected)
Greater than or equal
assert_lte(actual, expected)
Less than or equal
assert_has(collection, item)
Collection contains item
assert_does_not_have(collection, item)
Collection does not contain item
assert_string_contains(str, sub)
String contains substring
assert_almost_eq(actual, expected, margin)
Float equality within margin
assert_signal_emitted(obj, signal_name)
Signal was emitted
assert_signal_not_emitted(obj, signal_name)
Signal was not emitted
断言说明
assert_eq(actual, expected)
相等
assert_ne(actual, expected)
不相等
assert_true(value)
为真值
assert_false(value)
为假值
assert_null(value)
为 null
assert_not_null(value)
不为 null
assert_gt(actual, expected)
大于
assert_lt(actual, expected)
小于
assert_gte(actual, expected)
大于或等于
assert_lte(actual, expected)
小于或等于
assert_has(collection, item)
集合包含该项
assert_does_not_have(collection, item)
集合不包含该项
assert_string_contains(str, sub)
字符串包含子字符串
assert_almost_eq(actual, expected, margin)
浮点数在误差范围内相等
assert_signal_emitted(obj, signal_name)
信号已发出
assert_signal_not_emitted(obj, signal_name)
信号未发出

gdUnit4 assertions (GDScript + C#)

gdUnit4 断言(GDScript + C#)

GDScriptC#Description
assert_that(val).is_equal(exp)
AssertThat(val).IsEqual(exp)
Equality
assert_that(val).is_not_equal(exp)
AssertThat(val).IsNotEqual(exp)
Not equal
assert_that(val).is_true()
AssertThat(val).IsTrue()
Is true
assert_that(val).is_false()
AssertThat(val).IsFalse()
Is false
assert_that(val).is_null()
AssertThat(val).IsNull()
Is null
assert_that(val).is_not_null()
AssertThat(val).IsNotNull()
Is not null
assert_that(val).is_greater(exp)
AssertThat(val).IsGreater(exp)
Greater than
assert_that(val).is_less(exp)
AssertThat(val).IsLess(exp)
Less than
assert_that(val).is_between(min, max)
AssertThat(val).IsBetween(min, max)
In range (inclusive)
assert_that(arr).contains([a, b])
AssertThat(arr).Contains(a, b)
Array contains elements
assert_that(str).contains("sub")
AssertThat(str).Contains("sub")
String contains substring
assert_that(val).is_equal_approx(exp, margin)
AssertThat(val).IsEqualApprox(exp, margin)
Float within margin
await assert_signal(mon).is_emitted("name")
await AssertSignal(node).IsEmitted("name")
Signal emitted

GDScriptC#说明
assert_that(val).is_equal(exp)
AssertThat(val).IsEqual(exp)
相等
assert_that(val).is_not_equal(exp)
AssertThat(val).IsNotEqual(exp)
不相等
assert_that(val).is_true()
AssertThat(val).IsTrue()
为 true
assert_that(val).is_false()
AssertThat(val).IsFalse()
为 false
assert_that(val).is_null()
AssertThat(val).IsNull()
为 null
assert_that(val).is_not_null()
AssertThat(val).IsNotNull()
不为 null
assert_that(val).is_greater(exp)
AssertThat(val).IsGreater(exp)
大于
assert_that(val).is_less(exp)
AssertThat(val).IsLess(exp)
小于
assert_that(val).is_between(min, max)
AssertThat(val).IsBetween(min, max)
在范围内(含边界)
assert_that(arr).contains([a, b])
AssertThat(arr).Contains(a, b)
数组包含元素
assert_that(str).contains("sub")
AssertThat(str).Contains("sub")
字符串包含子字符串
assert_that(val).is_equal_approx(exp, margin)
AssertThat(val).IsEqualApprox(exp, margin)
浮点数在误差范围内
await assert_signal(mon).is_emitted("name")
await AssertSignal(node).IsEmitted("name")
信号已发出

What NOT to Test

不应测试的内容

Avoid testing things that add noise without catching real bugs:
  • Godot engine internals — do not assert that
    Node.add_child()
    works or that
    @export
    variables show up in the editor
  • Private implementation details — test behavior through the public API; if a refactor breaks a test that covers only private state, the test is wrong
  • Visual/rendering output — pixel-level rendering results are brittle; test the data driving the visuals instead
  • Timing-sensitive floats without margins — use
    assert_almost_eq
    /
    IsEqualApprox
    for physics values
  • One-liners that wrap a built-in — a property getter that just returns a field needs no test
  • Every possible invalid input — test the documented contract, not every imaginable misuse

避免测试那些只会增加噪声、却无法发现实际缺陷的内容:
  • Godot 引擎内部机制——不要断言
    Node.add_child()
    能正常工作,或
    @export
    变量会显示在编辑器中
  • 私有实现细节——通过公共 API 测试行为;如果重构破坏了一个仅覆盖私有状态的测试,那么该测试本身就是错误的
  • 视觉和渲染输出——像素级渲染结果容易变得不稳定;应改为测试驱动视觉表现的数据
  • 没有误差范围的时序敏感浮点数——对于物理数值,使用
    assert_almost_eq
    /
    IsEqualApprox
  • 仅包装内置功能的一行代码——如果属性 getter 只是返回某个字段,则无需测试
  • 每一种可能的无效输入——应测试已记录的契约,而不是每一种可以想象的误用方式

Checklist

检查清单

  • Each test file matches the naming convention for the chosen framework (GUT
    test_*.gd
    ; gdUnit4
    *_test.gd
    /
    *Test.cs
    )
  • Tests extend the correct base class (
    GutTest
    /
    GdUnitTestSuite
    ); C# gdUnit4 suites are plain
    [TestSuite]
    classes
  • C#:
    gdUnit4.api
    pinned to 4.3.x on Godot 4.3; on 5.x (Godot 4.4+), suites that touch nodes or scenes carry
    [RequireGodotRuntime]
  • Nodes added to the scene tree use
    add_child_autofree
    or
    auto_free
    — never manual
    queue_free()
  • Signals are watched before the action that triggers them
  • Mocks/doubles are used for external dependencies, not for the unit under test
  • Each test covers exactly one behavior (one logical assertion per test)
  • CI workflow runs tests headlessly on every push and PR
  • Flaky async tests use explicit timeouts, not arbitrary sleep durations
  • Tests pass before merging (RED is only acceptable while actively implementing)
  • 每个测试文件都符合所选框架的命名约定(GUT 使用
    test_*.gd
    ;gdUnit4 使用
    *_test.gd
    /
    *Test.cs
    )
  • 测试继承正确的基类(
    GutTest
    /
    GdUnitTestSuite
    );C# gdUnit4 测试套件是普通的
    [TestSuite]
    类
  • C#:在 Godot 4.3 上将
    gdUnit4.api
    固定为 4.3.x;在 5.x(Godot 4.4+)上,涉及节点或场景的测试套件需要添加
    [RequireGodotRuntime]
  • 添加到场景树的节点使用
    add_child_autofree
    或
    auto_free
    ,绝不手动调用
    queue_free()
  • 在执行触发信号的操作之前监听信号
  • Mock/Double 用于外部依赖,而不是被测试单元本身
  • 每个测试只覆盖一种行为(每个测试只有一个逻辑断言)
  • CI 工作流在每次 push 和 PR 时以 headless 模式运行测试
  • 不稳定的异步测试使用明确的超时时间,而不是任意设置 sleep 时长
  • 合并前测试必须通过(只有在 actively implementing 期间才允许处于 RED 状态)