Posted at

MSTestでのテストクラスの継承とTestInitialize/TestCleanup

More than 5 years have passed since last update.

テストクラスを継承した場合、Initialize/Cleanup系がどのように動作するのか調べてみた。


まとめ


  • 基底クラスで定義されたものはTestInitialize/TestCleanupのみ呼ばれる。

  • 基底クラスではTestInitializeAttributeがついたメソッドは複数定義可能だが、実体側ではひとつのみ定義可能(Exception)。

表にすると次の通り。

種類
基底クラス
派生クラス(実体)

AssemblyInitialize
×

ClassInitialize
×

TestInitialize

TestCleanup

ClassCleanup
×

AssemblyInitialize
×


コード

public class MyTestClassBase

{
[AssemblyInitialize]
public static void BaseAssemblyIntiialize()
{
System.Diagnostics.Trace.WriteLine("BaseAssemblyIntiialize");
}

[ClassInitialize]
public static void BaseClassInitialize()
{
System.Diagnostics.Trace.WriteLine("BaseClassInitialize");
}

[TestInitialize]
public void BaseTestInitialize()
{
System.Diagnostics.Trace.WriteLine("BaseTestInitialize");
}

[TestInitialize]
public void BaseTestInitialize2()
{
System.Diagnostics.Trace.WriteLine("BaseTestInitialize2");
}

[TestCleanup]
public void BaseTestCleanup()
{
System.Diagnostics.Trace.WriteLine("BaseTestCleanup");
}

[ClassCleanup]
public static void BaseCleanup()
{
System.Diagnostics.Trace.WriteLine("BaseCleanup");
}

[AssemblyCleanup]
public static void BaseAssemblyCleanup()
{
System.Diagnostics.Trace.WriteLine("BaseAssemblyCleanup");
}
}

[TestClass]
public class MyTestClass : MyTestClassBase
{
[AssemblyInitialize]
public static void AssemblyIntiialize(TestContext testContext)
{
System.Diagnostics.Trace.WriteLine("AssemblyIntiialize");
}

[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
System.Diagnostics.Trace.WriteLine("ClassInitialize");
}

[TestInitialize]
public void TestInitialize()
{
System.Diagnostics.Trace.WriteLine("TestInitialize");
}

/* -> Exception!!
[TestInitialize]
public void TestInitialize2()
{
System.Diagnostics.Trace.WriteLine("TestInitialize2");
}*/

[TestCleanup]
public void TestCleanup()
{
System.Diagnostics.Trace.WriteLine("TestCleanup");
}

[ClassCleanup]
public static void ClassCleanup()
{
System.Diagnostics.Trace.WriteLine("TestClassCleanup");
}

[AssemblyCleanup]
public static void AssemblyCleanup()
{
System.Diagnostics.Trace.WriteLine("AssemblyCleanup");
}

[TestMethod]
public void TestMethod()
{
System.Diagnostics.Trace.WriteLine("TestMethod");
}


結果

ClassInitialize

BaseTestInitialize2
BaseTestInitialize
TestInitialize
TestMethod
TestCleanup
BaseTestCleanup
TestClassCleanup