필터 지우기
필터 지우기

Can I access local functions for unit testing

조회 수: 7 (최근 30일)
Jason Klebes
Jason Klebes 2023년 2월 20일
댓글: Daniel 2023년 8월 3일
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