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();
    }
}

これを実行すると、コンソールウィンドウに以下の 2 つの警告が表示されます。

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 は新しいルールセットファイルを使用してアセンブリを再コンパイルします。再コンパイルの後、コンソールウィンドウに以下の 2 つのメッセージが表示されます。

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 がプロジェクトを再度コンパイルすると、コンソールウィンドウに以下のメッセージが表示されます。

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 リポジトリへのリンクです。

ユニットテスト
スクリプティングの概念