クラスを使用するセットアップ コードと破棄コードの記述
この例では、クラスベースのテスト用にメソッド レベルおよびクラス レベルでセットアップ コードおよび破棄コードを実装する方法を示します。
テスト フィクスチャ
"テスト フィクスチャ" とは、システムのテスト前の状態を設定するセットアップ コードと、テストの実行後にそれを元の状態に戻す破棄コードです。セットアップ メソッドおよび破棄メソッドは、TestCase クラスで以下のメソッドの属性により定義されます。
TestMethodSetupメソッドとTestMethodTeardownメソッドは、各Testメソッドの前と後に実行します。TestClassSetupメソッドとTestClassTeardownメソッドは、テスト クラスのすべてのTestメソッドの前と後に実行します。
テスト フレームワークは、スーパークラスの TestMethodSetup メソッドと TestClassSetup メソッドをサブクラスのメソッドの前に実行します。
TestMethodTeardown および TestClassTeardown methods ブロック内の対応する破棄メソッドを実装する代わりに、addTeardown メソッドを使用して TestMethodSetup および TestClassSetup methods ブロック内からすべての破棄アクションを行うことをお勧めします。元の状態変化の直前または直後に、例外をスローする可能性のある他のコードを挟むことなく、addTeardown を呼び出します。addTeardown を使用することで、テスト フレームワークがセットアップ コードの逆の順番で破棄コードを実行でき、また例外セーフなテスト内容が作成されます。
メソッド レベルのセットアップ コードをもつテスト ケース
FigurePropertiesTest クラスは Figure のプロパティをテストします。メソッド レベルのセットアップ コードおよび破棄コードが含まれています。TestMethodSetup メソッドはそれぞれのテストの実行前に Figure を作成し、TestMethodTeardown メソッドは後でその Figure を閉じます。前述のとおり、addTeardown メソッドにより破棄アクションを定義するようにすべきです。ただし、この例では説明を分かりやすくするため TestMethodTeardown methods ブロックの実装方法を示します。
classdef FigurePropertiesTest < matlab.unittest.TestCase properties TestFigure end methods (TestMethodSetup) function createFigure(testCase) testCase.TestFigure = figure; end end methods (TestMethodTeardown) function closeFigure(testCase) close(testCase.TestFigure) end end methods (Test) function defaultCurrentPoint(testCase) cp = testCase.TestFigure.CurrentPoint; testCase.verifyEqual(cp,[0 0], ... "Default current point must be [0 0].") end function defaultCurrentObject(testCase) import matlab.unittest.constraints.IsEmpty co = testCase.TestFigure.CurrentObject; testCase.verifyThat(co,IsEmpty, ... "Default current object must be empty.") end end end
クラス レベルのセットアップ コードをもつテスト ケース
CurrencyFormatTest クラスは数値の通貨表示形式をテストします。クラス レベルのセットアップ コードおよび破棄コードが含まれています。テストを実行する前に、TestClassSetup メソッドは数値の出力表示形式を小数点以下 2 桁の通貨形式に変更します。クラス内のすべてのテストが実行された後に、addTeardown メソッドを呼び出して表示形式を元の状態に戻します。この例では説明のために TestClassSetup methods ブロックの実装方法を示します。実際には、クラス レベルでセットアップ アクションおよび破棄アクションを実行するのは、テストごとにこれらのアクションを繰り返すと時間がかかって非効率的である場合に役立ちます。
classdef CurrencyFormatTest < matlab.unittest.TestCase methods (TestClassSetup) function setFormat(testCase) originalFormat = format; testCase.addTeardown(@format,originalFormat) format Bank end end methods (Test) function truncationTest(testCase) actual = strtrim(formattedDisplayText(pi)); expected = "3.14"; testCase.verifyEqual(actual,expected) end function divisionTest(testCase) actual = strtrim(formattedDisplayText(100/3)); expected = "33.33"; testCase.verifyEqual(actual,expected) end function negativeValueTest(testCase) actual = strtrim(formattedDisplayText(-1)); expected = "-1.00"; testCase.verifyEqual(actual,expected) end end end
参考
matlab.unittest.TestCase | addTeardown