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

조회 수: 1 (최근 30일)
Randy Strauss
Randy Strauss 2020년 4월 7일
편집: matquest 2020년 4월 7일
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