我正在使用 MATLAB xUnit测试一些代码。我希望能够直接调用包含在 private
目录中的一些函数。
这是一个简单的可复制设置:
创建一个包含两个文件夹 code
和 test
的项目目录。在 code
中,创建一个名为 private
的子目录,这样你的目录树看起来像
project_root
code
private
test
在code
目录下放一个函数
function y = main()
y = sub();
end
在 private
目录下放置一个函数
function y = sub()
y = 123;
end
在 test
目录下放置一个函数
function testsub()
assertElementsAlmostEqual(sub(), 123);
end
现在导航到测试目录并调用 runtests
。您应该会看到一条错误消息,指出 sub
未定义。
private
目录不允许出现在 matlab 路径上,因此这不是一个选项。我可能会在 code
目录中放置一个函数来检索所有私有(private)函数的句柄,但这看起来很老套。
获取访问权限以测试私有(private)函数的最佳方式是什么?
编辑:
导航到私有(private)目录的思路有问题。理论上我可以调用,例如,
cd(privateDirectory);
suite = TestSuite.fromName(testDirectory);
suite.run
不幸的是,一旦您调用 run
,测试框架就会导航到包含测试的目录。
最佳答案
一个解决方案是从 testsub
导航到私有(private)目录,得到 function handle使用 STR2FUNC 到您想要的私有(private)函数,然后导航回来使用该函数句柄进行测试。您甚至可以将这些步骤放在单独的辅助函数中进行单元测试,如下所示:
function privateFcn = get_private_fcn(privateDir,fcnName)
oldDir = cd(privateDir); %# Change to the private directory
privateFcn = str2func(fcnName); %# Get a function handle
cd(oldDir); %# Change back to the original directory
end
您将在 testsub
中使用此函数,如下所示:
function testsub()
privateDir = '...\project_root\code\private'; %# The path to the private
%# directory
privateFcn = get_private_fcn(privateDir,'sub'); %# Call get_private_fcn
assertElementsAlmostEqual(privateFcn(), 123); %# Apply your test
end
虽然 MATLAB 编辑器给了我一个 M-Lint,但这是有效的使用函数 CD 的警告:“MCC使用CD功能有问题。”我认为忽略此警告对您来说是安全的,因为 1) 函数 get_private_fcn
更改了当前目录,然后在获取函数句柄后立即将其更改回来,并且 2) 您不是 dealing with a deployed application .
关于unit-testing - 如何测试私有(private)目录中的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4500103/