How can I make my test find a second function in a neighboring file?

1 次查看(过去 30 天)
I inherited some matlab files and I want to write tests for them.
Each file contains multiple function declarations.
It seems like I can only access the top-level function. How do I make tests for the other functions?
(I did the OnRamp course...)
File: toBeTested.m
function value = toBeTested(x)
value = toBeTested2(x) - 1;
end
function value = toBeTested2(x)
value = x;
end
File: toBeTestedTest.m
function tests = toBeTestedTest
tests = functiontests(localfunctions);
end
function setupOnce(~)
addpath .. .
end
function test1(testCase)
which test1
which toBeTested % this is found...
verifyEqual(testCase, 1, toBeTested(2));
end
function test2(testCase)
which test2
which toBeTested2 % this says it can't be found :?(
verifyEqual(testCase, 2, toBeTested2(2)); % This fails, with an error
end
When I open the file in the LiveEditor, it prompts me with a RunTests button.
The test1 passes. test2 fails with:
Error occurred in toBeTestedTest/test2 and it did not run to completion.
---------
Error ID:
---------
'MATLAB:UndefinedFunction'
--------------
Error Details:
--------------
Undefined function 'toBeTested2' for input arguments of type 'double'.
Error in toBeTestedTest>test2 (line 18)
verifyEqual(testCase, 2, toBeTested2(2));

采纳的回答

matquest
matquest 2020-4-7
编辑:matquest 2020-4-7
See the accepted answer to this related question: Multiple functions in one .m file, but the upshot is that unfortunately you cannot do what you're trying to.
I actually have been in a similar situation recently and there are two main options that I was able to identify:
  1. Convert the functions to classes. Then you can create a "unit_tests" function that you can call
  2. Change the function that has the same name as the file (e.g., if your file is named "complicated_stuff.m" the function header would look like function output = complicated_stuff([args]) to use varargin. Then do potentially horribly inelegant stuff to check the number of inputs and redirect to a unit_tests function at the bottom.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Write Unit Tests 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by