程序集重复引用 % 错误CS0246
我想在Unity项目中创建单元测试,但总是遇到两类问题中的一种(甚至两者都遇到):
- 程序集存在重复引用
- 错误CS0246:类型或命名空间名称 '...' 无法找到(是否缺少using指令或程序集引用?)
如何同时修复这两个问题?
- 框架:Unity测试框架
- Unity项目结构:
none
Project
|_ Assets
|_ Editor
|_ editor_script.cs
|_ Plugins
|_ Sub_1/Editor
|_ Sub_1.asmdef
|_ *.cs
|_ Sub_2/Editor
|_ *.cs
|_ Sub_n
|_ *.cs
|_ Scripts
|_ *.cs
|_ Sub_n
|_ *.cs
|_ Settings/Build_Profiles
|_ <empty>
|_ Tests
|_ EditMode
|_ EditMode.asmdef
|_ Test_edit.cs
|_ PlayMode
|_ PlayMode.asmdef
|_ Test_play.cs
|_ Other folders without any .cs files
|_ CodeCoverage
|_ Library
|_ ScriptAssemblies
|_ IngameDebugConsole.Editor.dll
|_ IngameDebugConsole.Runtime.dll
|_ Unity.Burst.dll
|_ Unity.Burst.Editor.dll
|_ Unity.Collections.Editor.dll
|_ Unity.Collections.dll
|_ Unity.InputSystem.dll
|_ Unity.InputSystem.TestFramework.dll
|_ Unity.TestTools.CodeCoverage.Editor.dll
|_ UnityEditor.TestRunner.dll
|_ UnityEngine.TestRunner.dll
|_ Logs
|_ Packages
|_ manifest.json
|_ package-lock.json
|_ ProjectSettings
|_ Temp
|_ UserSettings
* EditMode.asmdef
json
{
"name": "Game.EditModeTests",
"references": [
"UnityEngine.TestRunner",
"UnityEngine.TestRunner.NUnit",
"Assembly-CSharp-Editor"
],
"includePlatforms": [
"Editor"
],
"testAssembly": true
}
* PlayMode.asmdef
json
{
"name": "Game.PlayModeTests",
"references": [
"UnityEngine.TestRunner",
"UnityEngine.TestRunner.NUnit",
"Assembly-CSharp"
],
"testAssembly": true
}
* Test_edit.cs (示例)
```cs using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; using System.Collections;
namespace GeneratedTests.EditMode { [TestFixture] public class ClassName_Tests {
[Test]
public void New_Test()
{
var obj = new ClassName();
Assert.IsNotNull(obj);
}
}
}
``
*Test_play.cs` (示例)
```cs using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; using System.Collections;
namespace GeneratedTests.PlayMode { [TestFixture] public class ClassName_Tests {
[Test]
public void New_Test()
{
var obj = new ClassName();
Assert.IsNotNull(obj);
}
}
} ```
解决方案
你不能随意把脚本放在顶层文件夹里,不把它们放进命名空间,也不把它们与测试关联起来就指望一切都会顺利。
如果你创建了一个Scripts文件夹,把脚本放进去,并创建一个名为Game.Scripts的 asmdef,然后在测试中引用它,编译就没问题。
-- MyScripts.asmdef
{
"name": "MyScripts",
}
-- 为避免混淆,下面的内容是在上述基础上修改后的版本,展示了包含所需类的MyScripts的引入。
-- PlayMode.asmdef
{
"name": "Game.PlayModeTests",
"references": [
"UnityEngine.TestRunner",
"UnityEngine.TestRunner.NUnit",
"Assembly-CSharp",
"MyScripts"
],
"testAssembly": true
}
--EditMode.asmdef
{
"name": "Game.EditModeTests",
"references": [
"UnityEngine.TestRunner",
"UnityEngine.TestRunner.NUnit",
"Assembly-CSharp-Editor",
"MyScripts"
],
"includePlatforms": [
"Editor"
],
"testAssembly": true
}