MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Create Custom Constraint


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

In a file in your working folder, create a 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 Constraint
implementations are immutable, set the property SetAccess attribute to immutable.

classdef HasSameSizeAs < matlab.unittest.constraints.Constraint

properties(SetAccess=immutable)
ValueWithExpectedSize
end

methods
function constraint = HasSameSizeAs(value)
constraint.ValueWithExpectedSize = value;
end
end
end

Classes that derive from Constraint must implement the satisfiedBy method. This
method must contain the comparison logic and return a boolean value.

Include the satisfiedBy method in the methods block in HasSameSizeAs.m.

function bool = satisfiedBy(constraint, actual)
bool = isequal(size(actual), size(constraint.ValueWithExpectedSize));
end

If the actual size and expected size are equal, this method returns true.

Classes deriving from Constraint must implement the getDiagnosticFor method.
This method must evaluate the actual value against the constraint and provide a
Diagnostic object. In this example, getDiagnosticFor returns a
StringDiagnostic. Include the getDiagnosticFor method in the methods block in
HasSameSizeAs.m.

function diag = getDiagnosticFor(constraint, actual)
import matlab.unittest.diagnostics.StringDiagnostic

33 Unit Testing

Free download pdf