Version: 2022.2
包布局
为资源包创建示例

向包添加测试

As with any kind of development, it’s good practice to add tests to your package. There are three things you must do to set up tests on your package:

  1. 创建 C# 测试文件并将测试文件放在 Tests 文件夹下
  2. 为测试创建 asmdef 文件
  3. 为包启用测试

测试文件的位置

可以将测试文件添加到包的 Tests 文件夹的 Editor 和 Runtime 子文件夹中。例如,一个包含测试的简单包可能如下所示:

MyPackage
  ├── package.json
  ├── Editor
  │     ├── MyPackage.Editor.asmdef
  │     └── EditorExample.cs
  ├── Runtime
  │     ├── MyPackage.Runtime.asmdef
  │     └── RuntimeExample.cs
  └── Tests
        ├── Editor
        │    ├── MyPackage.EditorTests.asmdef
        │    └── EditorExampleTest.cs
        └── Runtime
             ├── MyPackage.RuntimeTests.asmdef
             └── RuntimeExampleTest.cs

每个子文件夹必须包含一个 .asmdef 文件,该文件提供对 Editor 和 Runtime 程序集的引用。程序集定义文件还提供对测试程序集文件的引用。有关更多信息,请参阅用于测试的程序集定义文件

用于测试的程序集定义文件

可以直接编辑程序集定义文件。需要确保添加以下引用:

属性 类型 描述
name String 程序集的名称(不含文件扩展名)。
references 字符串数组 References to the Editor and Runtime assemblies. Assembly definition files require different references, depending on the test type:
- For Editor tests, add a reference to the package’s Editor and Runtime assemblies.
- For Runtime tests, add a reference to the package’s Runtime assembly only.
optionalUnityReferences 字符串数组 This list of Unity references must include "TestAssemblies" to mark the assembly as a test assembly. This adds references to the nunit.framework.dll and UnityEngine.TestRunner.dll libraries to the Assembly Definition.
includePlatforms 字符串数组 For the Editor test, this list of platforms must include the "Editor" platform.

提示:还可以在 Inspector 中编辑程序集定义文件。请参阅程序集定义以了解更多信息。

Editor 文件示例

Editor 测试 .asmdef 文件应如下所示:

{
  "name": "MyPackage.Editor.Tests",
  "references": [
    "MyPackage.Editor",
    "MyPackage"
  ],
  "optionalUnityReferences": [
    "TestAssemblies"
  ],
  "includePlatforms": [
    "Editor"
  ],
  "excludePlatforms": []
}

运行时文件示例

运行时测试 .asmdef 文件应如下所示:

{
  "name": "MyPackage.Tests",
  "references": [
    "MyPackage"
  ],
  "optionalUnityReferences": [
    "TestAssemblies"
  ],
  "includePlatforms": [],
  "excludePlatforms": []
}

为包启用测试

对于嵌入式包,不需要显式启用测试,因为嵌入式包正在开发中。

但是,对于其他类型的依赖项,则需要向项目清单添加 testables 属性,并添加包含待运行测试的包名称。这包括项目的直接依赖项和间接依赖项。例如:

{
  "dependencies": {
    "com.unity.some-package": "1.0.0",
    "com.unity.other-package": "2.0.0",
    "com.unity.yet-another-package": "3.0.0",
  },
  "testables": ["com.unity.some-package", "com.unity.other-package"]
}

This example adds tests for the com.unity.some-package and com.unity.other-package packages in Unity’s Test Framework package.

Note: You might need to import the package again, because the test framework doesn’t always immediately pick up changes to the testables attribute.

包布局
为资源包创建示例