【问题标题】:Import functions in Matlab for every local function在 Matlab 中为每个局部函数导入函数
【发布时间】:2016-01-03 16:24:01
【问题描述】:

我有一个m-file,其中有几个测试定义为本地函数。它们是从主函数调用的:

function tests = main_function_test()
    tests = functiontests(localfunctions);
end

我正在做一些容忍的断言,所以我需要在每个本地函数中导入:

import matlab.unittest.constraints.IsEqualTo;
import matlab.unittest.constraints.AbsoluteTolerance;

为了做出如下形式的断言:

verifyThat(testCase, actual, IsEqualTo(expected, ...
        'Within', AbsoluteTolerance(0.00001)));

是否可以只导入一次这些函数,以便在每个本地函数中重复使用它们?

【问题讨论】:

  • 没有。每the documentation:Scope is the function and the function does not share the import list of the parent function. If the import list is needed in a MATLAB function or script and in any local functions, you must call the import function for each function.
  • 谢谢,@excaza,我没有找到那个摘录。您可以将此添加为答案。除非存在一些技巧,否则我想这应该是公认的答案。

标签: matlab unit-testing


【解决方案1】:

这是不可能的 the documentation:

作用域是函数,函数不共享父函数的导入列表。如果 MATLAB 函数或脚本以及任何本地函数中需要导入列表,则必须为每个函数调用导入函数。

话虽如此,您可以evalimport(字符串单元数组)的输出一起使用,但这是极差的编码习惯,我强烈建议不要这样做。

function trialcode
import matlab.unittest.constraints.IsEqualTo;
import matlab.unittest.constraints.AbsoluteTolerance;

importlist = import;
sub1(importlist)
end

function sub1(L)
for ii = 1:length(L)
    estr = sprintf('import %s', L{ii});
    eval(estr);
end
disp(import)
end

同样,这在技术上是可行的,但请不要这样做。您对导入几乎没有控制权(控制逻辑可能比一开始隐式导入它们要长),难以调试,MATLAB 的编译器无法优化,并且使代码非常不清楚。

【讨论】:

    【解决方案2】:

    您可以在这里做两件事。

    1. 使用 verifyEqual 函数 (doc) 获得 verifyThat 的大部分功能。请注意,该函数存在 'RelTol''AbsTol' 名称值对。

    2. 定义特殊的局部函数以使用类似 import 语句。这些将在文件中具有优先级,就像您对文件级导入所期望的一样。

    看起来像这样:

    function tests = main_function_test()
    tests = functiontests(localfunctions);
    end
    
    function firstTest(testCase)
    testCase.verifyThat(actual, IsEqualTo(expected, ...
            'Within', AbsoluteTolerance(0.00001)));
    end
    
    function testASecondThing(testCase)
    testCase.verifyThat(actual, IsEqualTo(expected, ...
            'Within', RelativeTolerance(0.0005)));
    end
    
    % "import" functions
    function c = IsEqualTo(varargin)
    c = matlab.unittest.constraints.IsEqualTo(varargin{:});
    end
    function t = AbsoluteTolerance(varargin)
    t = matlab.unittest.constraints.AbsoluteTolerance(varargin{:});
    end
    function t = RelativeTolerance(varargin)
    t = matlab.unittest.constraints.RelativeTolerance(varargin{:});
    end
    

    希望有帮助!

    【讨论】:

    • 您的回答触发了我另一个选择:在另一个名为 verify_almost_equal(testCase,actual,expected,tol) 的文件中定义一个新的辅助函数,这将是唯一一个进行导入的文件。这样我就可以在多个测试文件中重复使用它。
    猜你喜欢
    • 2014-05-10
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 2011-07-24
    • 2011-02-19
    • 1970-01-01
    相关资源
    最近更新 更多