В этом примере показано, как создать пользовательское булево ограничение, которое определяет, имеет ли данное значение тот же размер как ожидаемое значение.
В файле в вашей текущей папке создайте класс под названием 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