В этом примере показано, как создать пользовательское логическое ограничение, определяющее, имеет ли данное значение тот же размер, что и ожидаемое значение.
В файле текущей папки создайте класс с именем HasSameSizeAs которая происходит от matlab.unittest.constraints.BooleanConstraint класс. Конструктор класса принимает ожидаемое значение, размер которого сравнивается с размером фактического значения. Ожидаемое значение сохраняется в ValueWithExpectedSize собственность. Рекомендуемая практика состоит в том, чтобы BooleanConstraint реализации незыблемы, поэтому задайте свойство SetAccess атрибут для immutable.
classdef HasSameSizeAs < matlab.unittest.constraints.BooleanConstraint properties(SetAccess = immutable) ValueWithExpectedSize end methods function constraint = HasSameSizeAs(value) constraint.ValueWithExpectedSize = value; end end end
В methods блок с private доступ, определение вспомогательного метода sizeMatchesExpected определяет, имеют ли фактические и ожидаемые значения одинаковый размер. Этот метод вызывается другими методами ограничения.
methods(Access = private) function bool = sizeMatchesExpected(constraint,actual) bool = isequal(size(actual),size(constraint.ValueWithExpectedSize)); end end
matlab.unittest.constraints.BooleanConstraint класс является подклассом matlab.unittest.constraints.Constraint класс. Следовательно, классы, производные от BooleanConstraint класс должен переопределять методы Constraint класс. В пределах methods блок, переопределить satisfiedBy и getDiagnosticFor методы. satisfiedBy реализация должна содержать логику сравнения и возвращать логическое значение. getDiagnosticFor реализация должна оценивать фактическое значение по ограничению и предоставлять Diagnostic объект. В этом примере: getDiagnosticFor возвращает StringDiagnostic объект.
methods function bool = satisfiedBy(constraint,actual) bool = constraint.sizeMatchesExpected(actual); end function diag = getDiagnosticFor(constraint,actual) import matlab.unittest.diagnostics.StringDiagnostic if constraint.sizeMatchesExpected(actual) diag = StringDiagnostic('HasSameSizeAs passed.'); else diag = StringDiagnostic(sprintf(... 'HasSameSizeAs failed.\nActual Size: [%s]\nExpectedSize: [%s]',... int2str(size(actual)),... int2str(size(constraint.ValueWithExpectedSize)))); end end end
Классы, производные от BooleanConstraint должны реализовывать getNegativeDiagnosticFor способ. Этот метод должен обеспечивать Diagnostic объект при отрицании ограничения.
Отвергнуть getNegativeDiagnosticFor в methods блок с protected доступ.
methods(Access = protected) function diag = getNegativeDiagnosticFor(constraint,actual) import matlab.unittest.diagnostics.StringDiagnostic if constraint.sizeMatchesExpected(actual) diag = StringDiagnostic(sprintf(... ['Negated HasSameSizeAs failed.\nSize [%s] of '... 'Actual Value and Expected Value were the same '... 'but should not have been.'],int2str(size(actual)))); else diag = StringDiagnostic('Negated HasSameSizeAs passed.'); end end end
В обмен на внедрение требуемых методов ограничение наследует соответствующее and, or, и not перегрузки, чтобы ее можно было комбинировать с другими BooleanConstraint объекты или сведенные на нет.
Это полный код для HasSameSizeAs класс.
classdef HasSameSizeAs < matlab.unittest.constraints.BooleanConstraint properties(SetAccess = immutable) ValueWithExpectedSize end methods function constraint = HasSameSizeAs(value) constraint.ValueWithExpectedSize = value; end function bool = satisfiedBy(constraint,actual) bool = constraint.sizeMatchesExpected(actual); end function diag = getDiagnosticFor(constraint,actual) import matlab.unittest.diagnostics.StringDiagnostic if constraint.sizeMatchesExpected(actual) diag = StringDiagnostic('HasSameSizeAs passed.'); else diag = StringDiagnostic(sprintf(... 'HasSameSizeAs failed.\nActual Size: [%s]\nExpectedSize: [%s]',... int2str(size(actual)),... int2str(size(constraint.ValueWithExpectedSize)))); end end end methods(Access = protected) function diag = getNegativeDiagnosticFor(constraint,actual) import matlab.unittest.diagnostics.StringDiagnostic if constraint.sizeMatchesExpected(actual) diag = StringDiagnostic(sprintf(... ['Negated HasSameSizeAs failed.\nSize [%s] of '... 'Actual Value and Expected Value were the same '... 'but should not have been.'],int2str(size(actual)))); else diag = StringDiagnostic('Negated HasSameSizeAs passed.'); end end end methods(Access = private) function bool = sizeMatchesExpected(constraint,actual) bool = isequal(size(actual),size(constraint.ValueWithExpectedSize)); end end end
В командной строке создайте тестовый пример для интерактивного тестирования.
import matlab.unittest.TestCase import matlab.unittest.constraints.HasLength testCase = TestCase.forInteractiveUse;
Проверьте проходной случай. Тест завершается успешно, потому что один из or условия, HasLength(5), это правда.
testCase.verifyThat(zeros(5),HasLength(5) | ~HasSameSizeAs(repmat(1,5)))
Verification passed.
Проверьте неуспешный случай. Тест завершается неуспешно, поскольку один из and условия, ~HasSameSizeAs(repmat(1,5)), является ложным.
testCase.verifyThat(zeros(5),HasLength(5) & ~HasSameSizeAs(repmat(1,5)))
Verification failed.
---------------------
Framework Diagnostic:
---------------------
AndConstraint failed.
--> + [First Condition]:
| HasLength passed.
|
| Actual Value:
| 0 0 0 0 0
| 0 0 0 0 0
| 0 0 0 0 0
| 0 0 0 0 0
| 0 0 0 0 0
| Expected Length:
| 5
--> AND
+ [Second Condition]:
| Negated HasSameSizeAs failed.
| Size [5 5] of Actual Value and Expected Value were the same but should not have been.
-+---------------------getDiagnosticFor | getNegativeDiagnosticFor | matlab.unittest.constraints.BooleanConstraint | matlab.unittest.constraints.Constraint | matlab.unittest.diagnostics.Diagnostic | matlab.unittest.diagnostics.StringDiagnostic | satisfiedBy