【问题标题】:Creating parametrized Matlab unittest with complicated properties创建具有复杂属性的参数化 Matlab 单元测试
【发布时间】:2016-02-09 14:58:34
【问题描述】:

我正在尝试创建一个参数化的 Matlab 单元测试,其中 TestParameter 属性由某些代码“动态”生成(例如,使用 for 循环)。

作为一个简化的例子,假设我的代码是

classdef partest < matlab.unittest.TestCase
    properties (TestParameter)
        level = struct('level1', 1, 'level2', 2, 'level3', 3, 'level4', 4)
    end

    methods (Test)
        function testModeling(testCase, level)
            fprintf('Testing level %d\n', level);
        end
    end
end

但在我的真实代码中,我有 100 个级别。我试图把它放在一个单独的方法中,比如

classdef partest < matlab.unittest.TestCase
    methods (Static)
        function level = getLevel()
            for i=1:100
               level.(sprintf('Level%d', i)) = i;
            end
        end
    end

    properties (TestParameter)
        level = partest.getLevel()
    end

    methods (Test)
        function testModeling(testCase, level)
            fprintf('Testing level %d\n', level);
        end
    end
end

但这不起作用;我收到错误(Matlab 2014b):

>> runtests partest
Error using matlab.unittest.TestSuite.fromFile (line 163)
The class partest has no property or method named 'getLevel'.

我可以将getLevel() 函数移动到另一个文件中,但我想将它保存在一个文件中。

【问题讨论】:

  • 我无法运行你的代码,因为我的 matlab 版本太旧了,但你可以在原来的课程中尝试level = cell2struct(num2cell(1:n), arrayfun(@(x)(['level',num2str(x)]),1:n,'uni',false), 2)
  • @Daniel:当然我的真实例子更复杂:)

标签: matlab unit-testing parameterized-unit-test


【解决方案1】:

此处相同 (R2015b),看起来 TestParameter 属性无法使用静态函数调用进行初始化...

幸运的是,解决方案非常简单,请改用local function

partest.m

classdef partest < matlab.unittest.TestCase
    properties (TestParameter)
        level = getLevel()
    end

    methods (Test)
        function testModeling(testCase, level)
            fprintf('Testing level %d\n', level);
        end
    end
end

function level = getLevel()
    for i=1:100
       level.(sprintf('Level%d', i)) = i;
    end
end

(请注意,以上所有代码都包含在一个文件partest.m中)。

现在应该可以了:

>> run(matlab.unittest.TestSuite.fromFile('partest.m'))

注意

作为一个本地函数,它在课堂之外是不可见的。如果您还需要公开它,只需添加一个静态函数作为简单的包装器:

classdef partest < matlab.unittest.TestCase
    ...

    methods (Static)
        function level = GetLevelFunc()
            level = getLevel();
        end
    end
end

function level = getLevel()
    ...
end

【讨论】:

  • 我的 Java 背景真傻,我从来没有意识到我可以在 classdef 中创建本地函数。
  • 在文档中有一个关于它的条目:mathworks.com/help/matlab/matlab_oop/…
  • 这是一个错误:您应该能够通过调用类的静态方法来定义TestParameter。我已经向开发团队报告了这个错误,以便在未来的版本中修复。与此同时,正如 Amro 建议的那样,使用本地函数是一个很好的解决方法。
  • @FrankMeulenaar:这是错误报告:mathworks.com/support/bugreports/1212962
  • 从 R2016b 开始,此错误已得到修复。
猜你喜欢
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多