This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

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
        function constraint = HasSameSizeAs(value)
            constraint.ValueWithExpectedSize = value;

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

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.');
                diag = StringDiagnostic(sprintf(...
                    'HasSameSizeAs failed.\nActual Size: [%s]\nExpectedSize: [%s]',...

 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