В этом примере показано, как создать пользовательское логическое ограничение, которое определяет, имеет ли заданное значение тот же размер, что и ожидаемое значение.
В файле в текущей папке создайте класс с именем 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 access, задайте вспомогательный метод sizeMatchesExpected который определяет, имеют ли фактическое и ожидаемые значения одинаковый размер. Этот метод вызывается другими методами ограничений.
methods(Access = private) function bool = sizeMatchesExpected(constraint,actual) bool = isequal(size(actual),size(constraint.ValueWithExpectedSize)); end end
The matlab.unittest.constraints.BooleanConstraint класс является подклассом matlab.unittest.constraints.Constraint класс. Поэтому классы, которые получают из BooleanConstraint класс должен переопределить методы Constraint класс. В пределах methods блокируйте, переопределяйте satisfiedBy и getDiagnosticFor методы. The satisfiedBy реализация должна содержать логику сравнения и возвращать логическое значение. The 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