Test fixtures является настройкой и кодом отключения, который настраивает предварительное состояние системы и возвращает его в исходное состояние после запущения теста. Setup и методы отключения заданы в TestCase класс следующими атрибутами метода:
TestMethodSetup и TestMethodTeardown методы запущены до и после каждого метода тестирования.
TestClassSetup и TestClassTeardown методы, запущенные до и после всех методов тестирования в тесте.
Среда тестирования гарантирует тот TestMethodSetup и TestClassSetup методы суперклассов выполняются перед теми в подклассах.
Это - хорошая практика для тестовых авторов, чтобы выполнить все действия отключения из TestMethodSetup и TestClassSetup блоки с помощью addTeardown метод вместо того, чтобы реализовать соответствующие методы отключения в TestMethodTeardown и TestClassTeardown блоки. Это гарантирует, что отключение выполняется в обратном порядке настройки и также гарантирует, что содержание теста является безопасным исключением.
Следующий тест, FigurePropertiesTest, содержит код настройки на уровне метода. TestMethodSetup метод создает фигуру прежде, чем запустить каждый тест и TestMethodTeardown закрывает фигуру впоследствии. Как обсуждено ранее, необходимо попытаться задать действия отключения с addTeardown метод. Однако в иллюстративных целях, этот пример показывает реализацию TestMethodTeardown блок.
classdef FigurePropertiesTest < matlab.unittest.TestCase properties TestFigure end methods(TestMethodSetup) function createFigure(testCase) % comment testCase.TestFigure = figure; end end methods(TestMethodTeardown) function closeFigure(testCase) close(testCase.TestFigure) end end methods(Test) function defaultCurrentPoint(testCase) cp = testCase.TestFigure.CurrentPoint; testCase.verifyEqual(cp, [0 0], ... 'Default current point is incorrect') end function defaultCurrentObject(testCase) import matlab.unittest.constraints.IsEmpty co = testCase.TestFigure.CurrentObject; testCase.verifyThat(co, IsEmpty, ... 'Default current object should be empty') end end end
Следующий тест, BankAccountTest, содержит код настройки на уровне класса.
Устанавливать BankAccountTest, который тестирует BankAccount пример класса, описанный в Разработке Классов — Типичный Рабочий процесс, добавляет TestClassSetup метод, addBankAccountClassToPath. Этот метод добавляет путь к BankAccount файл в качестве примера. Как правило, вы создаете путь с помощью PathFixture. Этот пример выполняет настройку и действия отключения вручную в иллюстративных целях.
classdef BankAccountTest < matlab.unittest.TestCase % Tests the BankAccount class. methods (TestClassSetup) function addBankAccountClassToPath(testCase) p = path; testCase.addTeardown(@path,p); addpath(fullfile(matlabroot,'help','techdoc','matlab_oop',... 'examples')); end end methods (Test) function testConstructor(testCase) b = BankAccount(1234, 100); testCase.verifyEqual(b.AccountNumber, 1234, ... 'Constructor failed to correctly set account number'); testCase.verifyEqual(b.AccountBalance, 100, ... 'Constructor failed to correctly set account balance'); end function testConstructorNotEnoughInputs(testCase) import matlab.unittest.constraints.Throws; testCase.verifyThat(@()BankAccount, ... Throws('MATLAB:minrhs')); end function testDesposit(testCase) b = BankAccount(1234, 100); b.deposit(25); testCase.verifyEqual(b.AccountBalance, 125); end function testWithdraw(testCase) b = BankAccount(1234, 100); b.withdraw(25); testCase.verifyEqual(b.AccountBalance, 75); end function testNotifyInsufficientFunds(testCase) callbackExecuted = false; function testCallback(~,~) callbackExecuted = true; end b = BankAccount(1234, 100); b.addlistener('InsufficientFunds', @testCallback); b.withdraw(50); testCase.assertFalse(callbackExecuted, ... 'The callback should not have executed yet'); b.withdraw(60); testCase.verifyTrue(callbackExecuted, ... 'The listener callback should have fired'); end end end
addTeardown | matlab.unittest.TestCase