Main Content

addTeardown

类: matlab.unittest.TestCase
命名空间: matlab.unittest

向测试用例动态添加拆解代码

说明

addTeardown(testCase,teardownFcn) 可向测试用例注册拆解代码 teardownFcn。要在测试运行时动态运行拆解代码,请在 Test 方法、TestMethodSetup 方法或 TestClassSetup 方法中使用 addTeardown。拆解操作的时间和频率取决于调用方法的作用域:

  • Test 方法 - teardownFcn 在当前测试后运行。

  • TestMethodSetup 方法 - teardownFcn 在测试类中的每个测试后运行。

  • TestClassSetup 方法 - teardownFcn 在类中的所有测试后运行一次。

为了还原环境,该方法会强制应用后进先出 (LIFO) 策略,使拆解操作以与其对应的设置操作相反的顺序执行。使用 addTeardown 获得满足异常安全条件的测试内容。

示例

addTeardown(testCase,teardownFcn,input1,...,inputN) 还可指定调用 teardownFcn 来拆解脚手架时使用的输入参数。

输入参数

全部展开

测试用例,指定为 matlab.unittest.TestCase 对象。

拆解代码,指定为函数句柄。

示例: addTeardown(testCase,@() format(originalFormat))

用于调用函数句柄 teardownFcn 以拆解脚手架的输入参数,指定为以逗号分隔的值列表。

示例: addTeardown(testCase,@close,fig)

示例: addTeardown(testCase,@setenv,"UserName",originalUserName)

属性

Sealedtrue

要了解方法的属性,请参阅方法属性

示例

全部展开

在每次测试运行后动态执行拆解代码。

在当前文件夹的一个文件中创建 FigurePropertiesTest 类。在类中定义两个 Test 方法,每个方法验证一个图窗属性。要为每个测试创建一个刷新图窗,请使用 TestMethodSetup methods 代码块。要在每次测试后还原环境,请在同一个代码块中调用 addTeardown 方法。

classdef FigurePropertiesTest < matlab.unittest.TestCase
    properties
        TestFigure
    end

    methods (TestMethodSetup)
        function createFigure(testCase)
            testCase.TestFigure = figure;
            testCase.addTeardown(@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

运行测试。一旦一个测试运行完毕,测试框架就会通过调用传递给 addTeardown 的函数句柄自动关闭该测试的图窗。

results = runtests("FigurePropertiesTest");
Running FigurePropertiesTest
.
.
Done FigurePropertiesTest
__________

详细信息

全部展开

版本历史记录

在 R2013a 中推出