以下の内容はhttps://www.hanachiru-blog.com/entry/2023/12/21/120000より取得しました。


【C#, Unity】Test FrameworkにてType判定するときのIs.TypeOfとIs.InstanceOfの挙動の違いについて

はじめに

今回はNUnit.Framework.Is.TypeOfNUnit.Framework.Is.InstanceOfで挙動が異なることについて書きたいと思います。

private abstract class HogeBase { }

private class Hoge : HogeBase { }
    
[Test]
public void SampleTestSimplePasses()
{
    Hoge hoge = new Hoge();
        
    // Failed
    // Is.EqualToを利用したパターン (Tests exact type)
    Assert.That(hoge.GetType(), Is.EqualTo(typeof(HogeBase)));
        
    // Failed
    // Is.TypeOfを利用したパターン (Tests exact type)
    Assert.That(hoge, Is.TypeOf<HogeBase>());
    Assert.That(hoge, Is.TypeOf(typeof(HogeBase)));
        
    // Passed
    // Is.InstanceOfを利用したパターン (Tests type and subtype)
    Assert.That(hoge, Is.InstanceOf<HogeBase>());
    Assert.That(hoge, Is.InstanceOf(typeof(HogeBase)));

    // Passed
    // Assert.IsInstanceOfを利用したパターン (Tests type and subtype)
    Assert.IsInstanceOf<HogeBase>(hoge);
    Assert.IsInstanceOf(typeof(HogeBase), hoge);
}

違いについて

最初に貼ったコードで大体雰囲気を掴めたかと思いますが以下の違いがあります。

  • Is.TypeOf : 指定された型ならtrueを返す
  • Is.InstanceOf : 指定された型かその派生型ならtrueを返す

// Is.TypeOf
Returns a constraint that tests whether the actual value is of the exact type supplied as an argument.

// DeepL翻訳
実際の値が、引数として提供された正確な型であるかどうかをテストする制約を返します。

learn.microsoft.com

// Is.InstanceOf
実際の値が引数として指定された型か派生型かをテストする制約を返します。

learn.microsoft.com




以上の内容はhttps://www.hanachiru-blog.com/entry/2023/12/21/120000より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14