Version: 2020.2
单元测试。
脚本概念

Roslyn 分析器和规则集文件

在 Unity 项目中使用 Roslyn 分析器规则集文件,可检查代码的样式、质量和其他问题。

You can use existing analyzer libraries to inspect your code, as well as write your own analyzers to promote the best practices or conventions within your organization. This page explains how to use Roslyn analyzers in an empty Unity Project.

使用现有的 Roslyn 分析器库

To use an existing Roslyn analyzer library, install the ErrorProne.NET.CoreAnalyzers library from NuGet inside your project. Then open the .csproj file. There are three .dll files included in the project as analyzers:

  <ItemGroup>
      <Analyzer Include="packages\ErrorProne.NET.CoreAnalyzers.0.1.2\analyzers\dotnet\cs\ErrorProne.NET.Core.dll" />
      <Analyzer Include="packages\ErrorProne.NET.CoreAnalyzers.0.1.2\analyzers\dotnet\cs\ErrorProne.Net.CoreAnalyzers.dll" />
      <Analyzer Include="packages\ErrorProne.NET.CoreAnalyzers.0.1.2\analyzers\dotnet\cs\RuntimeContracts.dll" />
    </ItemGroup>

Move the three .dll files into the Assets folder (or any folder nested in the Assets folder) in your Unity project. In the Editor, select the .dll file. In the Plugin Inspector, under Select platforms for plugin, disable Any Platform. Under Include platforms, disable Editor and Standalone platforms. Then, give all of the DLLs a new label called RoslynAnalyzer.

To test that everything works correctly, save a file named RethrowError.cs with the following code in your project’s Assets folder. This code causes ErrorProne.NET to raise warnings about incorrect exception propagation and suspicious exception handling:

using System;
using UnityEngine;

public class RethrowError : MonoBehaviour
{
    void Update()
    {
        try
        {
            DoSomethingInteresting();
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
            throw e;
        }
    }

    private void DoSomethingInteresting()
    {
        throw new System.NotImplementedException();
    }
}

执行此操作后,您应该会在 Console 窗口中看到以下两个警告:

Assets\RethrowError.cs(14,23): warning EPC12: Suspicious exception handling: only e.Message is observed in exception block.
Assets\RethrowError.cs(15,19): warning ERP021: Incorrect exception propagation.Use throw; instead.

规则集文件

要定义如何处理项目中的分析器引发的各种警告和错误的规则,您可以创建规则集文件。有关如何创建自定义规则集的更多信息,请参阅 Microsoft 的 Visual Studio 文档如何创建自定义规则集

In the Assets root folder, place a ruleset file named Default.ruleset. The rules you define in Default.ruleset apply to all predefined assemblies (for example Assembly-CSharp.dll), as well as all assemblies that are built using .asmdef files.

To override the rules in Default.ruleset for a predefined assembly, create a .ruleset file in the root folder with the name [PredefinedAssemblyName].ruleset. For example, the rules in Assembly-CSharp.ruleset apply to the code in Assembly-CSharp.dll. Only these .ruleset files are permitted inside the root folder:

  • Default.ruleset
  • Assembly-CSharp.ruleset
  • Assembly-CSharp-firstpass.ruleset
  • Assembly-CSharp-Editor.ruleset
  • Assembly-CSharp-Editor-firstpass.ruleset

工作流程:在 Unity 中测试规则集文件

要在 Unity 中测试规则集文件,请执行以下步骤:

步骤 1:设置规则集文件

  1. 在项目的 Assets 文件夹中创建一个名为 Subfolder 的子文件夹。
  2. Subfolder 内:
    1. 创建一个新的 .asmdef 文件。
    2. 保存 RethrowError.cs 的重复副本。
  3. Assets 中创建一个 Default.ruleset 文件,包含如下代码:
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="New Rule Set" Description=" " ToolsVersion="10.0">
  <Rules AnalyzerId="ErrorProne.NET.CodeAnalyzers" RuleNamespace="ErrorProne.NET.CodeAnalyzers">
    <Rule Id="ERP021" Action="Error" />
  <Rule Id="EPC12" Action="None" />
  </Rules>
</RuleSet>

Default.ruleset 文件定义了以下规则:

  • 将关于可疑异常处理的警告的 EPC12 禁止。
  • 将关于错误异常传播的警告的 ERP021 提升为错误。

第 2 步:重新加载项目

将规则集文件添加到您的项目后,重新导入程序集中需应用规则的任何脚本。这会强制 Unity 使用新的规则集文件重新编译程序集。重新编译后,您应该在 Console 窗口中看到两条消息:

Assets\Subfolder\RethrowError.cs(15,19): error ERP021: Incorrect exception propagation.Use throw; instead.
Assets\RethrowError.cs(15,19): error ERP021: Incorrect exception propagation.Use throw; instead.

请注意,Unity 将 Default.ruleset 中定义的规则应用到 Assets/RethrowError.csAssets/Subfolder/RethrowError.cs

第 3 步:添加自定义规则集

Assets/Subfolder,创建一个 .ruleset 文件,并根据您的喜好命名(本例中为 Hello.ruleset):

<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="New Rule Set" Description=" " ToolsVersion="10.0">
  <Rules AnalyzerId="ErrorProne.NET.CodeAnalyzers" RuleNamespace="ErrorProne.NET.CodeAnalyzers">
    <Rule Id="ERP021" Action="Info" />
    <Rule Id="EPC12" Action="Info" />
  </Rules>
</RuleSet>

这个新的 Hello.ruleset 文件告诉 Unity 将 EPC12ERP021 打印到控制台,而不将它们视为警告或错误。

Unity 再次编译项目后,您会在 Console 窗口中看到以下消息:

Assets\Subfolder\RethrowError.cs(14,23): info EPC12: Suspicious exception handling: only e.Message is observed in exception block.
Assets\Subfolder\RethrowError.cs(15,19): info ERP021: Incorrect exception propagation.Use throw; instead.
Assets\RethrowError.cs(15,19): error ERP021: Incorrect exception propagation.Use throw; instead.

Default.ruleset 中的规则仍然应用于 Assets\RethrowError.cs,但它们不再应用于 Assets\Subfolder\RethrowError.cs,因为 Hello.ruleset 中的规则将其覆盖。

有关所有允许的规则集操作文件的更多信息,请参阅 Visual Studio 文档使用代码分析规则集编辑器

More analyzers

以下是指向其他流行 Roslyn 分析器库的 Github 存储库的链接:

*Roslyn 分析器兼容性添加于 2020.2 NewIn20202

单元测试。
脚本概念