Accelerating the pace of engineering and science

# matlab.unittest.constraints.HasElementCount class

Package: matlab.unittest.constraints
Superclasses: matlab.unittest.constraints.BooleanConstraint

Constraint specifying expected number of elements

## Construction

HasElementCount(countVal) provides a constraint that specifies an expected number of elements. The constraint is satisfied if the actual value array has the same number of elements specified as by countVal.

### Input Arguments

 countVal Number of elements a value must have to satisfy the constraint.

## Properties

 Count Number of elements a value must have to satisfy the constraint. Set this property through the constructor via the countVal input argument.

## Copy Semantics

Value. To learn how value classes affect copy operations, see Copying Objects in the MATLAB® documentation.

## Examples

expand all

### Test for Expected Number of Elements

Create a test case for interactive testing.

```import matlab.unittest.TestCase
import matlab.unittest.constraints.HasElementCount

testCase = TestCase.forInteractiveUse;```

Verify a scalar has an element count of one.

`testCase.verifyThat(3, HasElementCount(1))`
`Interactive verification passed.`

Test the element count of the vector.

`testCase.assertThat([42 7 13], HasElementCount(3))`
`Interactive assertion passed.`

Test the element count of the matrix.

`testCase.assertThat([1 2 3; 4 5 6], HasElementCount(5))`
```Interactive assertion failed.

---------------------
Framework Diagnostic:
---------------------
HasElementCount failed.
--> The value did not have the correct number of elements.

Actual Number of Elements:
6
Expected Number of Elements:
5

Actual Value:
1     2     3
4     5     6
Assertion failed.```

The matrix has six elements.

Test that a square identity matrix has the correct number of elements.

```n = 7;
testCase.assumeThat(eye(n), HasElementCount(n^2))```
`Interactive assumption passed.`

Verify the element count of a cell array of strings.

`testCase.verifyThat({'aString', 'anotherString'}, HasElementCount(2))`
`Interactive verification passed.`

Test the element count of a structure.

```s.Field1 = 1;
s.Field2 = 2;
testCase.verifyThat(s, HasElementCount(2))```
```Interactive verification failed.

---------------------
Framework Diagnostic:
---------------------
HasElementCount failed.
--> The value did not have the correct number of elements.

Actual Number of Elements:
1
Expected Number of Elements:
2

Actual Value:
Field1: 1
Field2: 2```

The structure has two fields, but it only has one element.

`testCase.verifyThat(s, HasElementCount(1))`
`Interactive verification passed.`