Main Content

使用类来编写设置代码和拆解代码

此示例说明如何在基于类的测试的方法级和类级实现设置和拆解代码。

测试脚手架

测试脚手架是设置和拆解代码,用于设置系统的预测试状态并在运行测试后将其恢复为原始状态。设置和拆解方法在 TestCase 类中由以下方法属性定义:

  • TestMethodSetupTestMethodTeardown 方法在每个 Test 方法之前和之后运行。

  • TestClassSetupTestClassTeardown 方法在测试类中的所有 Test 方法之前和之后运行。

测试框架先执行超类的 TestMethodSetupTestClassSetup 方法,再执行子类中对应方法。

最好使用 addTeardown 方法从 TestMethodSetupTestClassSetupmethods 块中执行所有拆解活动,而不是在 TestMethodTeardownTestClassTeardown methods 块中实现相应的拆解方法。在原始状态更改之前或之后立即调用 addTeardown,中间没有任何可能引发异常的其他代码。使用 addTeardown 这种方式允许测试框架以与设置代码相反的顺序执行拆解代码,并且还创建满足异常安全要求的测试内容。

包含方法级设置代码的测试用例

FigurePropertiesTest 类测试图窗的属性。它包含方法级的设置和拆解代码。TestMethodSetup 方法在运行每个测试之前创建一个图窗,TestMethodTeardown 方法在运行测试之后关闭图窗。如前所述,您应该尽量使用 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 方法将数值的输出显示格式更改为小数点后两位数的货币格式。在类中的所有测试运行后,对 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

另请参阅

|

相关主题