В этом примере показано, как создать пользовательское булево ограничение, которое определяет, имеет ли данное значение тот же размер как ожидаемое значение.
В файле в вашей текущей папке создайте класс под названием 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;
Протестируйте передающий случай.
testCase.verifyThat(zeros(5),HasLength(5) | ~HasSameSizeAs(repmat(1,5)))
Verification passed.
Тест передает потому что один из or условия, HasLength(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.
-+---------------------Тест перестал работать потому что один из and условия, ~HasSameSizeAs(repmat(1,5)), является ложным.
getDiagnosticFor | getNegativeDiagnosticFor | matlab.unittest.constraints.BooleanConstraint | matlab.unittest.constraints.Constraint | satisfiedBy