Can I access local functions for unit testing
16 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
Jan
on 20 Feb 2023
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
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 Comments
Steven Lord
on 1 Mar 2023
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
on 3 Aug 2023
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.
More Answers (0)
See Also
Categories
Find more on Testing Frameworks in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!