MATLAB:如何自动中止失败的单元测试

时间:2019-05-29 13:25:28

标签: matlab unit-testing

我想知道一旦被测系统(sut)发生错误,如何使单元测试自动停止?

让我们假设,单元测试可以运行大约1,000种不同的输入组合,并可以验证结果是否符合预期。现在,让我们进一步假设sut中存在一个简单的语法错误,该错误会导致错误。在这种情况下,我希望单元测试自动停止并调用拆卸方法。

有可能吗?

编辑:

我从他们的帮助站点(https://de.mathworks.com/help/matlab/matlab_prog/create-basic-parameterized-test.html)借用了一个MATLAB示例,以便更清楚地说明我的意思:

在这里您可以看到测试课程:

classdef TestCarpet < matlab.unittest.TestCase

    properties (TestParameter)
        type = {'single','double','uint16'};
        level = struct('small', 2,'medium', 4, 'large', 6);
        side = struct('small', 9, 'medium', 81,'large', 729);
    end

    methods (Test)
        function testRemainPixels(testCase, level)
            % expected number pixels equal to 1
            expPixelCount = 8^level;
            % actual number pixels equal to 1
            actPixels = find(sierpinski(level));
            testCase.verifyNumElements(actPixels,expPixelCount)
        end

        function testClass(testCase, type, level)
            testCase.verifyClass(...
                sierpinski(level,type), type)
        end

        function testDefaultL1Output(testCase)
            exp = single([1 1 1; 1 0 1; 1 1 1]);
            testCase.verifyEqual(sierpinski(1), exp)
        end
    end

    methods (Test, ParameterCombination='sequential')
        function testNumel(testCase, level, side)
            import matlab.unittest.constraints.HasElementCount
            testCase.verifyThat(sierpinski(level),...
                HasElementCount(side^2))
        end
    end
end

这是被测系统:

function carpet = sierpinski(nLevels,classname)
if nargin == 1
    classname = 'single';
end

% original line: mSize = 3^nLevels;
mSize = "That's clearly wrong here";
carpet = ones(mSize,classname);

cutCarpet(1,1,mSize,nLevels) % begin recursion

    function cutCarpet(x,y,s,cL)
        if cL
            ss = s/3; % define subsize
            for lx = 0:2
                for ly = 0:2
                    if lx == 1 && ly == 1  
                        % remove center square
                        carpet(x+ss:x+2*ss-1,y+ss:y+2*ss-1) = 0;
                    else
                        % recurse
                        cutCarpet(x + lx*ss, y + ly*ss, ss, cL-1)
                    end
                end
            end
        end
    end
end

我将mSize的定义更改为字符串以产生错误。现在,如果我运行测试,所有测试将导致错误。我想知道是否有可能尽快停止测试,即在出现第一个错误之后?

我看到的问题是测试代码甚至无法到达testRemainPixels (testCase.verifyNumElements(actPixels,expPixelCount))的最后一行。 fatalAssert在这一点上没有帮助,对吗?

1 个答案:

答案 0 :(得分:0)

假设您正在使用MATLAB内置的测试框架,请查看资格的类型,尤其是此页面顶部的项目符号列表:

https://www.mathworks.com/help/matlab/matlab_prog/types-of-qualifications.html

如果要停止整个测试会话,则可以使用致命断言。如果希望其他测试继续进行,则可以使用断言。如果要跳过单个文件中的所有测试方法(和参数化),则可以在TestClassSetup中使用断言,也可以在TestClassSetup中添加代码的基本“烟雾”级练习步骤,如果出错,它将表现为断言

希望有帮助。

相关问题