Understanding how testCase.addTeardown works with @path
15 views (last 30 days)
Show older comments
Diaa on 27 Jul 2022
Commented: Steven Lord on 27 Jul 2022
The following code is adopted from this blog post:
classdef GoodFixturesTest < matlab.unittest.TestCase
p = addpath(fullfile(pwd, 'path1'));
p = addpath(fullfile(pwd, 'path2'));
So, I need to deeply understand how addTeardown works in this line
to remove the search paths of path1 and path2 and restore the original search paths in view of
and the path function syntax path(newpath).
In other words, what is the meaning of passing all the search paths (including path1 and path2) stored in p to the function handle @path in order to restore the original search paths without the full paths of the newly added subfolders path1 and path2?
From the addpath documentation: "oldpath = addpath(___) additionally returns the path prior to adding the specified folders." So p does not include the path1 or path2 subdirectories (unless they were already on the path.)
This is a common pattern in MATLAB. Many functions that change some of the state of MATLAB return the state prior to the change to facilitate "undoing" the state change.
Of course, this example is a bit artificial to me. For this I wouldn't use addTeardown manually to restore the previous state. I'd create and apply a matlab.unittest.fixtures.PathFixture. The PathFixture will automatically restore the previous state of the path when it gets torn down.
Looking at the matlab.unittest.fixtures.PathFixture class documentation page, see the "Add Folders to the Path for Testing" example for a short demonstration of how to use the fixture. Note that there's no call to addTeardown in that code. Essentially the teardown was added by applyFixture when it applied the PathFixture to the test session.
Run that test several times under different configurations and examine the state of the path (using the path function) before and after each run.
- Neither folderA nor folderB are on the MATLAB path before the test executes. In this case they should be on the path during the execution of the test method after the fixture has been applied, but neither will be on the MATLAB path after the test executes.
- Only folderA (not folderB) is on the MATLAB path before the test executes. As above they will both be on the path during the test execution after the fixture has been applied, but only folderA will be on the MATLAB path after the test finishes its execution.
- Both folderA and folderB are on the MATLAB path before the test executes. They will remain on the MATLAB path during test execution and will remain on the MATLAB path after the test finishes executing.
More Answers (0)
Find more on Class-Based Unit Tests in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!