在 Unity3d 测试脚本中,如何从另一个 class 调用静态函数?

In Unity3d test scripts, how do I call a static function from another class?

我在 Unity3d 项目中有两个文件。一个是在编辑模式下运行的测试脚本。另一个是单个 class,带有我想从测试脚本中调用的静态函数。

这是我的测试脚本:

using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;

public class NewTestScript 
{

    [Test]
    public void TestAnotherStaticFunction() 
    {
        int a = NewBehaviourScript.FunctionUnderTest(1);
        int b = 1;

        // Use the Assert class to test conditions.
        Assert.IsTrue(a == b);
    }
}

这是我正在测试的函数:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour 
{
    /// <summary>
    /// the stupidest function in the world, 
    /// used to verify tests.
    /// </summary>
    public static int FunctionUnderTest(int a)
    {
        return a;
    }
}

Unity 编译器出现错误(我不是在 Unity 之外构建):

Assets/TestS/NewTestScript.cs(12,17):错误 CS0103:当前上下文中不存在名称“NewBehaviourScript”

这些 运行 处于编辑模式。

我尝试在被测函数和调用代码中添加和删除 SuperTestNameSpace 命名空间。

我已经尝试 .asmdef 文件中的 adding/removing 文件,这些文件是由 unity 自动生成的,尽管这通常会导致其他编译错误。

我之前的单元测试经验主要在Visual Studio或VSCode,我正在努力让我的unity3d测试经验匹配我之前的测试环境经验。

编辑模式测试中的功能是否存在根本性的限制,还是我遗漏了一些愚蠢的东西?

进一步详细说明所涉及的程序集。看起来这里有两个程序集在起作用:Assembly-CSharp.dll 包含我的测试代码,TestS.dll 包含我的测试代码。我相信我的问题归结为:如何将 TestS.dll 程序集的引用添加到 Assembly-CSharp.dll。我知道如何在 Visual Studio 中执行此操作(通过 VS 中的上下文菜单或直接编辑 csproj 文件),但我不知道如何在 Unity3d 中执行此操作。我对 csproj 文件所做的任何编辑经常被统一覆盖,虽然检查器中有一个 'references' 部分(见图)我无法添加 Assembly-CSharp.dll作为参考。

These are the inspector settings for TestS.asmdef. While there's an option to add references, I can't add a reference to Assembly-CSharp.dll, which is where my code-under-test lives.

主要问题是目前您正在尝试调用

NewBehaviourScript(1);

构造函数不存在...

而不是方法

using SuperTestNameSpace;

//...

NewBehaviourScript.FunctionUnderTest(1);

或者直接调用中的命名空间

SuperTestNameSpace.NewBehaviourScript.FunctionUnderTest(1);

还要确保文件名与 class 名称完全匹配。所以在你的情况下它应该是

NewBehaviourScript.cs

请注意 .cs 不是由 Unity 在 Project 视图中打印的,因此它应该显示 NewBehaviourScript.


为什么不能用 using SuperTestNameSpace; 编译?错误是什么?

如果那个异常

Assets/TestS/NewTestScript.cs(14,17): error CS0103: The name `NewBehaviourScript' does not exist in the current context

仅在 VisualStudio 中显示,但脚本在 Unity 中编译良好,尤其是在添加新脚本后,它有助于简单地关闭并重新启动 VS。

在某些情况下,它还有助于关闭 Unity 和 VS,删除除 AssetsProjectSettings 之外的所有文件和文件夹(如果您处于版本控制之下,则属于它的任何内容,例如 [ =20=、.gitignore.gitattributes 等),特别是删除 Library.vs 文件夹和所有 .csproj.sln 文件。

然后再次打开 Unity 并让它重新编译所有内容。

确保包含 NewBehaviourScript 的文件 class 在编辑器文件夹中。

移动资产(根)文件夹中的两个脚本,然后重试。

好的,我明白了。发生了两件事:

  1. 编辑器测试需要位于名为 editor 的文件夹下。 unity editor 不为你做这件事真的很烦人。
  2. 您需要为被测代码创建程序集定义并且将测试代码的引用添加到新创建的程序集定义中。此必须在Unity编辑器中完成UI。

默认情况下,unity 将您的脚本代码添加到名为 A​​ssembly-CSharp.dll 的程序集中,并且由于未知原因,我的编辑未引用此程序集模式测试代码。我不确定这是 Unity 中的错误还是设计使然,但明确创建和引用程序集定义已经解决了问题。