Main Content

matlab.unittest.constraints.HasUniqueElements 类

命名空间: matlab.unittest.constraints
超类: matlab.unittest.constraints.BooleanConstraint

测试集合是否有唯一元素

描述

matlab.unittest.constraints.HasUniqueElements 类提供一个约束来测试集合是否有唯一元素。

该约束使用 unique 函数来分析该集合。因此,unique 函数必须支持用于约束的实际值。

创建对象

描述

c = matlab.unittest.constraints.HasUniqueElements 创建一个约束来测试集合是否有唯一元素。对于实际集合 actual,如果 numel(unique(actual)) 等于 numel(actual),则满足约束。

示例

示例

全部折叠

使用 HasUniqueElements 约束测试集合。

首先,导入此示例中使用的类。

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

创建一个供交互测试的测试用例。

testCase = TestCase.forInteractiveUse;

验证 'abc' 是否由唯一字符组成。

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

使用 'Mississippi' 作为实际集合再次测试。测试失败,因为指定的值包含重复的字符。

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

验证数值矩阵 eye(5) 没有唯一元素。

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

测试数值向量 abs(-3:3) 是否有唯一元素。测试失败。

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

测试元胞数组 {'a','b','ab','bb'} 是否有唯一元素。测试通过。

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

使用 HasUniqueElements 约束测试具有唯一行的表。测试通过。

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

版本历史记录

在 R2016a 中推出