Main Content

matlab.unittest.constraints.HasUniqueElements Class

Namespace: matlab.unittest.constraints
Superclasses: matlab.unittest.constraints.BooleanConstraint

Test if set has unique elements

Description

The matlab.unittest.constraints.HasUniqueElements class provides a constraint to test if a set has unique elements.

The constraint uses the unique function to analyze the set. So, the actual value you use with the constraint must be supported by the unique function.

Creation

Description

example

c = matlab.unittest.constraints.HasUniqueElements creates a constraint to test if a set has unique elements. For an actual set actual, the constraint is satisfied if numel(unique(actual)) is equal to numel(actual).

Examples

collapse all

Test sets using the HasUniqueElements constraint.

First, import the classes used in this example.

import matlab.unittest.TestCase
import matlab.unittest.constraints.HasUniqueElements

Create a test case for interactive testing.

testCase = TestCase.forInteractiveUse;

Verify that 'abc' is composed of unique characters.

testCase.verifyThat('abc',HasUniqueElements)
Verification passed.

Test again with 'Mississippi' as the actual set. The test fails because the specified value contains repeated characters.

testCase.verifyThat('Mississippi',HasUniqueElements)
Verification failed.
    ---------------------
    Framework Diagnostic:
    ---------------------
    HasUniqueElements failed.
    --> The value contains 3 nonunique element(s):
        --> Nonunique element found at indices [2 5 8 11]:
                    i
        --> Nonunique element found at indices [9 10]:
                    p
        --> Nonunique element found at indices [3 4 6 7]:
                    s
    
    Actual char:
        Mississippi

Verify that the numeric matrix eye(5) does not have unique elements.

testCase.verifyThat(eye(5),~HasUniqueElements)
Verification passed.

Test if the numeric vector abs(-3:3) has unique elements. The test fails.

testCase.verifyThat(abs(-3:3),HasUniqueElements)
Verification failed.
    ---------------------
    Framework Diagnostic:
    ---------------------
    HasUniqueElements failed.
    --> The value contains 3 nonunique element(s):
        --> Nonunique element found at indices [3 5]:
                     1
        --> Nonunique element found at indices [2 6]:
                     2
        --> Nonunique element found at indices [1 7]:
                     3
    
    Actual Value:
         3     2     1     0     1     2     3

Test the cell array {'a','b','ab','bb'} for unique elements. The test passes.

testCase.verifyThat({'a','b','ab','bb'},HasUniqueElements)
Verification passed.

Test a table with unique rows using the HasUniqueElements constraint. The test passes.

T = table([3;3;5],{'A';'C';'E'},logical([1;0;0]));
testCase.verifyThat(T,HasUniqueElements)
Verification passed.

Version History

Introduced in R2016a