測試與除錯 (4.7)
執行測試: python scripts/test_run.py [--gd|--cs] [-a res://test/x] [--filter expr] 會回傳 {gd: {total, failed, failures: [{test, file, line, msg}]}, cs: {...}}。它先匯入資源,以無頭模式執行,並解析 JUnit/主控台結果。
在測試之前,請先編譯:../godot-gdscript/scripts/gd_check.py 與 ../godot-csharp/scripts/cs_build.py。使用 ../godot-core/scripts/run_godot.py smoke 快速執行遊戲。
GDScript:GdUnit4 (已驗證 6.2.2 on 4.7.2)
- 安裝:從 GitHub 發行版 (github.com/godot-gdunit-labs/gdUnit4, tag v6.2.x) 複製
addons/gdUnit4資料夾,並啟用外掛程式。測試檔案放在res://test/,且名稱結尾需為_test.gd。 - 測試套件
extends GdUnitTestSuite。測試方法為func test_*()。鉤子函式:before()、after()(套件層級)、before_test()、after_test()。 - 斷言:
assert_int/float/str/bool/vector/array/dict/object(x).is_equal(...)、assert_that(x)、assert_signal(obj).is_emitted("died")(需要先執行monitor_signals(obj))、assert_error(func() -> void: ...),以及await assert_func(obj, "is_ready").is_true()。 - 記憶體管理:將建立的物件包在
auto_free(...)中。報告會標記孤兒節點,請將其視為錯誤。 - 模擬物件:
mock(Class)+do_return(v).on(m).method()、spy(instance)、verify(m, times).method(args)、any_int()等。 - 整合測試:
var runner := scene_runner("res://player.tscn"),然後使用runner.simulate_action_pressed("jump")、await runner.simulate_frames(30)、runner.simulate_key_pressed(KEY_SPACE)、await runner.await_signal("landed")、runner.invoke("method")與runner.scene()。 - CLI (
test_run.py內部呼叫):godot --headless --path . -s -d res://addons/gdUnit4/bin/GdUnitCmdTool.gd --ignoreHeadlessMode -c -a res://test。結束代碼 0 表示成功,100 表示有失敗。報告為 JUnit XML 格式,存放在-rd指定的目錄下。
C#:gdUnit4Net (已驗證 Godot.NET.Sdk 4.7.2, .NET 10 SDK)
- 在遊戲的 csproj 中加入:
Microsoft.NET.Test.Sdk18.x、gdUnit4.api5.1.0-rc5 (adapter 3.1.1 需要 ≥5.1.0-rc5;5.0.0 還原時會因 NU1605 失敗)、gdUnit4.test.adapter3.1.1、gdUnit4.analyzers1.0.0,以及<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>。 - 加入
.runsettings檔案,內容包含<GdUnit4><Parameters>--headless</Parameters><GodotConnectTimeout>60000</GodotConnectTimeout></GdUnit4>。沒有這個設定,需要 Godot 執行階段的測試會因為連線逾時而失敗。使用GODOT_BIN=<godot 執行檔> dotnet test --settings .runsettings執行。 [TestSuite]類別、[TestCase]方法、[Before]/[After]/[BeforeTest]/[AfterTest]、[DataPoint(nameof(Cases))]用於參數化測試。使用using static GdUnit4.Assertions;→AssertThat(x).IsEqual(y)、AutoFree(node)。[RequireGodotRuntime]是任何觸及 Godot 型別(包括Mathf、節點與資源)的測試所必需的。否則分析器會報告GdUnit0501。純 C# 測試無需引擎即可執行,速度更快。- 場景:
ISceneRunner.Load("res://x.tscn")→SimulateFrames、SimulateActionPressed、AwaitSignal、Invoke。
測試什麼
純邏輯(傷害計算、物品欄、存檔遷移)作為快速的單元測試。場景透過場景執行器測試操控手感、UI 流程與信號連接。每個錯誤修正都應附帶回歸測試。保持測試套件快速,因為慢速套件最終會無人執行。
除錯
- 從編輯器執行 (F5) 可使用完整的除錯器:錯誤伴隨堆疊追蹤、中斷點(或
breakpoint陳述式)、逐步執行/跳出(Step Out 從 4.6 開始提供)、遠端場景樹(播放時即時檢視節點與屬性)、效能分析器、監控器與 ObjectDB 快照 (4.6)。 - 日誌:
print、print_rich("[color=yellow]...")、print_debug(附帶檔案與行號)、push_warning/push_error(在除錯器中顯示含堆疊的資訊,且非致命)、printerr。assert(cond, "msg")僅在除錯建置中執行,因此切勿在裡面放置副作用。 - 檔案日誌:
debug/file_logging/enable_file_logging(桌機預設啟用,user://logs/godot.log)。使用OS.get_user_data_dir()找到user://。 - 自訂
Logger(4.5+):建立子類別,覆寫_log_error/_log_message,並使用OS.add_logger()註冊。可用於遊戲內錯誤回報,搭配script_backtraces。啟用debug/settings/gdscript/always_track_call_stacks以在發行版建置中取得回溯資訊。Engine.capture_script_backtraces()可按需捕獲回溯。 - CLI:
-d(stdout 除錯器)、--verbose、--debug-collisions/--debug-navigation,以及--remote-debug tcp://host:6007用於將正在執行的建置附加到編輯器。 - C#:將 IDE 除錯器附加到遊戲程序 (Rider 與 VS Code C# Dev Kit 可以使用
--path啟動 Godot)。例外會被記錄,但非致命,請留意輸出面板。
快速閱讀錯誤
res://file.gd:LINE 指向出錯的行號。「null instance」表示節點路徑錯誤或在使用前就呼叫了 _ready。「previously freed」表示 await 或回呼的壽命超過了其所屬節點。「Parse Error」或「Compile Error」會阻止腳本載入,導致所有使用該腳本的內容都失敗,請優先修復第一個錯誤。「Condition "!is_inside_tree()" is true」表示在某個尚未加入場景樹的節點上呼叫了樹 API。引擎 C++ 檔案參考 (scene/main/node.cpp:123) 仍然代表你的呼叫有問題,請閱讀堆疊追蹤。
GdUnit 測試套件 (單元、模擬、信號、場景執行器)、C# 測試、遊戲內 Logger (由測試編譯):references/patterns.md