创建一个脚手架以从 MATLAB® 搜索路径中删除一个文件夹,并指示测试框架在脚手架失效时重置环境状态。然后,在多个类中运行测试时,将脚手架用作共享测试脚手架。
此示例假设路径中存在当前文件夹的子文件夹 helperFiles。如果该子文件夹不存在,请创建一个,并确保它在路径中。
在当前文件夹的一个文件中,创建一个名为 RemoveFolderFromPathFixture 的脚手架,它通过从路径中删除一个文件夹来设置环境状态。为了确保将该脚手架用作共享测试脚手架的所有测试类的环境状态相同,请覆盖 needsReset 方法。当测试运行器切换到后续类时,如果指定的文件夹在路径中,则该方法返回 true。
classdef RemoveFolderFromPathFixture < matlab.unittest.fixtures.Fixture
properties (SetAccess = immutable)
Folder (1,1) string % Full path to the folder
end
methods
function fixture = RemoveFolderFromPathFixture(folder)
fixture.Folder = folder;
end
function setup(fixture)
originalPath = path;
fixture.addTeardown(@()path(originalPath));
rmpath(fixture.Folder)
end
end
methods (Access = protected)
function tf = isCompatible(fixture1,fixture2)
tf = fixture1.Folder == fixture2.Folder;
end
function tf = needsReset(fixture)
foldersOnPath = split(path,pathsep);
tf = ismember(fixture.Folder,foldersOnPath);
end
end
end
在当前文件夹中,创建三个使用 RemoveFolderFromPathFixture 作为共享测试脚手架的测试类。
在名为 SampleTestA.m 的文件中,创建 SampleTestA 类。
classdef (SharedTestFixtures = { ...
RemoveFolderFromPathFixture(fullfile(pwd,'helperFiles'))}) ...
SampleTestA < matlab.unittest.TestCase
methods (Test)
function test1(testCase)
import matlab.unittest.constraints.ContainsSubstring
f = testCase.getSharedTestFixtures;
testCase.assertThat(path,~ContainsSubstring(f.Folder))
end
end
end
在名为 SampleTestB.m 的文件中,创建 SampleTestB 类。类中的测试将 helperFiles 添加到路径中。
classdef (SharedTestFixtures = { ...
RemoveFolderFromPathFixture(fullfile(pwd,'helperFiles'))}) ...
SampleTestB < matlab.unittest.TestCase
methods (Test)
function test1(testCase)
import matlab.unittest.constraints.ContainsSubstring
f = testCase.getSharedTestFixtures;
addpath('helperFiles')
testCase.assertThat(path,ContainsSubstring(f.Folder))
end
end
end
在名为 SampleTestC.m 的文件中,创建 SampleTestC 类。
classdef (SharedTestFixtures = { ...
RemoveFolderFromPathFixture(fullfile(pwd,'helperFiles'))}) ...
SampleTestC < matlab.unittest.TestCase
methods (Test)
function test1(testCase)
import matlab.unittest.constraints.ContainsSubstring
f = testCase.getSharedTestFixtures;
testCase.assertThat(path,~ContainsSubstring(f.Folder))
end
end
end
创建一个测试套件并运行测试。为了验证共享测试脚手架,当测试运行器切换到 SampleTestB 和 SampleTestC 时,测试框架调用 needsReset 方法。
Setting up RemoveFolderFromPathFixture
Done setting up RemoveFolderFromPathFixture
__________
Running SampleTestA
.
Done SampleTestA
__________
Running SampleTestB
.
Done SampleTestB
__________
Tearing down RemoveFolderFromPathFixture
Done tearing down RemoveFolderFromPathFixture
__________
Setting up RemoveFolderFromPathFixture
Done setting up RemoveFolderFromPathFixture
__________
Running SampleTestC
.
Done SampleTestC
__________
Tearing down RemoveFolderFromPathFixture
Done tearing down RemoveFolderFromPathFixture
__________
SampleTestA 不会破坏 RemoveFolderFromPathFixture 设置的环境状态。因此,框架使用已设置的脚手架来运行 SampleTestB。但是,SampleTestB 通过向路径添加 helperFiles 来破坏环境状态。该框架会拆解脚手架,并在调用 SampleTestB 和 SampleTestC 之间设置脚手架。