MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

function setup(fixture)
originalUserName = getenv('UserName');
fixture.assertNotEmpty(originalUserName, ...
'An existing UserName environment variable must be defined.')
fixture.addTeardown(@setenv, 'UserName', originalUserName)
fixture.TeardownDescription = sprintf(...
'Restored the UserName environment variable to "%s".',...
originalUserName);
setenv('UserName', fixture.UserName)
end
end


methods (Access=protected)
function bool = isCompatible(fixture, other)
bool = strcmp(fixture.UserName, other.UserName);
end
end
end


Apply Custom Fixture to Single Test Class


In a file in your working folder, create the following test class, ExampleTest.m.


classdef ExampleTest < matlab.unittest.TestCase
methods(TestMethodSetup)
function mySetup(testCase)
testCase.applyFixture(...
UserNameEnvironmentVariableFixture('David'));
end
end


methods (Test)
function t1(~)
fprintf(1, 'Current UserName: "%s"', getenv('UserName'))
end
end
end


This test uses the UserNameEnvironmentVariableFixture for each test in the
ExampleTest class.


At the command prompt, run the test.


run(ExampleTest);


Running ExampleTest
Current UserName: "David".
Done ExampleTest




Create Advanced Custom Fixture
Free download pdf