MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Create Custom Boolean Constraint


This example shows how to create a custom boolean constraint that determines if a given
value is the same size as an expected value.

In a file in your working folder, create a file HasSameSizeAs.m. The constructor accepts
a value to compare to the actual size. This value is stored within the
ValueWithExpectedSize property. Because it is recommended that
BooleanConstraint implementations be immutable, set the property SetAccess
attribute to immutable.
classdef HasSameSizeAs < matlab.unittest.constraints.BooleanConstraint
properties(SetAccess=immutable)
ValueWithExpectedSize
end
methods
function constraint = HasSameSizeAs(value)
constraint.ValueWithExpectedSize = value;
end
end
end

Include these methods in the methods block in HasSameSizeAs.m. Since the
BooleanConstraint class is a subclass of Constraint, classes that derive from it must
implement the satisfiedBy and getDiagnosticFor methods. For more information
about these methods, see matlab.unittest.constraints.Constraint.
methods
function bool = satisfiedBy(constraint, actual)
bool = isequal(size(actual), size(constraint.ValueWithExpectedSize));
end
function diag = getDiagnosticFor(constraint, actual)
import matlab.unittest.diagnostics.StringDiagnostic
if constraint.satisfiedBy(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

Include the getNegativeDiagnosticFor method in the methods block with protected
access in HasSameSizeAs.m. Classes that derive from BooleanConstraint must
implement the getNegativeDiagnosticFor method. This method must provide a
Diagnostic object that is expressed in the negative sense of the constraint.

Create Custom Boolean Constraint
Free download pdf