Borrar filtros
Borrar filtros

Can I access local functions for unit testing

7 visualizaciones (últimos 30 días)
Jason Klebes
Jason Klebes el 20 de Feb. de 2023
Comentada: Daniel el 3 de Ag. de 2023
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?

Respuesta aceptada

Jan
Jan el 20 de Feb. de 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
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 comentarios
Steven Lord
Steven Lord el 1 de Mzo. de 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
Daniel el 3 de Ag. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Testing Frameworks en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by