我有一个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)));
是否可以只导入一次这些函数,以便可以在每个本地函数中重用它们?
答案 0 :(得分:1)
Scope是函数,函数不共享父函数的导入列表。如果在MATLAB函数或脚本以及任何本地函数中需要导入列表,则必须为每个函数调用导入函数。
话虽如此,你可以使用eval
来自import
(字符串的单元格数组)的输出,但它的编码实践非常糟糕,我强烈建议不要这样做
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的编译器无法进行优化,并且使代码非常不清楚。
答案 1 :(得分:1)
你可以在这做两件事。
使用verifyEqual
功能(doc)获取verifyThat
的大部分功能。请注意,该函数存在'RelTol'
和'AbsTol'
名称值对。
定义要使用的特殊本地函数,例如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
希望有所帮助!