Can I access local functions for unit testing

12 次查看(过去 30 天)
I want to unit test local functions that appear after the main function of a file, whose name is not the file name. After all it's not really unit testing if I just test the final outcome of the program. Is there any way to call them from a test file? Do I really have to make a new file for every little helper function?

采纳的回答

Jan
Jan 2023-2-20
You can call subfunctions only from their main function. This impedes a unit-testing. But the main function can provide a function handle to the subfunction:
subFcnH = YourFcn('giveMeHandles');
subFcnH(0.1) - sin(0.1) % A simply unit-testing
ans = 0
function out = YourFcn(in)
% If input is a CHAR or string and equals a keyword:
if strcmpi(in, 'giveMeHandles')
out = @subFcn;
return;
end
% The actual calculation:
out = subFcn(in);
end
function y = subFcn(x)
y = sin(x);
end
  3 个评论
Steven Lord
Steven Lord 2023-3-1
Those local functions are only directly callable by code in that file. If you aren't already "exporting" them as function handles for some other purpose, shouldn't you be testing them through their interface (which would be the main function in the file)?
Daniel
Daniel 2023-8-3
Consider a large codebase with many files, each of which contains many local functions. The local functions behavior should be unit testable. Testing only through the main functions interface puts us at least one layer above the functionality under test, making it more difficult to write good tests. This should be obvious, so I won't provide any examples. Now, if in this example tests want to be added, the options to do so are pretty bad - either move all the local functions out into their own files, or modify the main function inputs and outputs (thus requiring modifications to instances throughout the codebase where the main functions are called) to return function handles to all local functions. Both of these options are pretty bad. In node, we could just export the local functions and then test them, without requiring any functional changes to the underlying codebase.
I hope that I am missing something here, but as far as I've been able to tell these are the only options to test local functions, both of which are really unfortunate.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Testing Frameworks 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by