functiontests not able to work properly in a for loop

조회 수: 4 (최근 30일)
Diego Luca de Tena
Diego Luca de Tena 2021년 9월 13일
답변: Abhas 2024년 5월 20일
Dear team,
I am trying to test a set of functions using functiontests each considering different datasets
For this, I have created a for loop that updates a global variable (timestamp) prior calling function tests.
Problem is that it only runs for the last element on the timestamp array.
Can you please provide guidance on how to overcome this issue?
Thanks
Diego
function tests = test_functionality
global timestamp;
addpath(genpath("../../../Source"));
timestamps_list = {'Xxx' 'Yyy'};
for i=1:size(timestamps_list,2)
timestamp = timestamps_list{i};
tests = functiontests(localfunctions);
end
end
  댓글 수: 1
Jan
Jan 2021년 9월 13일
Problem is that it only runs for the last element on the timestamp array.
timestamp is a scalar according to:
timestamp = timestamps_list{i};
So "the last" element of this array is "the only one" also. What else could happen?
What exactly is "it" in "it only runs"?

댓글을 달려면 로그인하십시오.

답변 (1개)

Abhas
Abhas 2024년 5월 20일
Hi Diego,
In the code, the loop is overwriting the 'tests' variable in each iteration, which results in only the last set of tests being returned. To store dynamically generated suite of tests, concatenate or collect these tests in an array that grows with each iteration of your loop.
Her's the MATLAB code to accumulate tests from all iterations into a single test suite:
function tests = test_functionality
global timestamp;
addpath(genpath("../../../Source"));
timestamps_list = {'Xxx', 'Yyy'};
tests = []; % Initialize an empty array to collect tests
for i = 1:length(timestamps_list)
timestamp = timestamps_list{i};
tempTests = functiontests(localfunctions);
tests = [tests, tempTests]; % Concatenate the new tests to the existing ones
end
end
The above code ensure that the 'test_functionality' function returns a suite of tests that includes tests generated for each timestamp of the 'timestamps_list', thereby overcoming the issue of only running tests for the last element.
You may refer to the following documentation links to have a better understanding of writing and dynamically storing tests:
  1. https://www.mathworks.com/help/matlab/matlab-unit-test-framework.html
  2. https://www.mathworks.com/help/matlab/math/creating-and-concatenating-matrices.html

카테고리

Help CenterFile Exchange에서 Testing Frameworks에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by