Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
|
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
我正在使用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 。 在matlab路径上不允许使用private目录,因此这不是一个选择。我可以在code目录中放置一个函数,以检索所有私有函数的句柄,但这似乎很麻烦。 访问测试私有功能的最佳方法是什么? 编辑: 导航到私有目录的想法有一个问题。从理论上讲,我可以称之为 cd(privateDirectory); suite = TestSuite.fromName(testDirectory); suite.run 不幸的是,一旦您调用run ,测试框架就会导航到包含测试的目录。 回答: 一个解决方案是从内浏览到私有目录testsub ,得到一个函数句柄您要使用的私有函数STR2FUNC ,然后导航回做使用该功能手柄进行测试。您甚至可以将这些步骤放在用于单元测试的单独的辅助函数中,如下所示: 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编辑器向我发出了使用功能CD的M-Lint警告,但这种方法仍然有效:“使用CD功能的MCC有问题。”我认为您可以忽略此警告,因为1)函数get_private_fcn更改了当前目录,然后在获得函数句柄后立即将其更改了; 2)您get_private_fcn 已部署的应用程序 。 更多&回答... |
![]() |
![]() |