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
            
            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

 HasSameSizeAs Class Definition Summary

At the command prompt, create a test case for interactive testing.

import matlab.unittest.TestCase

testCase = TestCase.forInteractiveUse;

Test a passing case.

testCase.verifyThat(zeros(5), HasSameSizeAs(repmat(1,5)))
Interactive verification passed.

Test a failing case.

testCase.verifyThat(zeros(5), HasSameSizeAs(ones(1,5)))
Interactive verification failed.

---------------------
Framework Diagnostic:
---------------------
HasSameSizeAs failed.
Actual Size: [5  5]
ExpectedSize: [1  5]

See Also

Related Topics