matlab-testing
This skill generates and executes MATLAB unit tests using the matlab.unittest framework, including class-based tests, parameterized testing, fixtures, mocking, coverage analysis, and App Designer testing. Use it when writing or running test suites, validating MATLAB code functionality, performing test-driven development, checking code coverage, or testing MATLAB apps with programmatic gestures.
git clone --depth 1 https://github.com/matlab/matlab-agentic-toolkit /tmp/matlab-testing && cp -r /tmp/matlab-testing/skills-catalog/matlab-core/matlab-testing ~/.claude/skills/matlab-testingSKILL.md
# Testing
Generate, structure, and run MATLAB unit tests using the `matlab.unittest` framework. Covers class-based tests, parameterized testing, fixtures, mocking, coverage analysis, CI/CD integration, and app testing via MCP.
## When to Use
- User asks to write tests for a MATLAB function or class
- User wants to run an existing test suite
- User needs coverage analysis or CI/CD configuration
- Test-driven development — writing tests before implementation
- Testing App Designer apps with programmatic gestures (see [reference/app-testing-guidance.md](reference/app-testing-guidance.md))
## When NOT to Use
- Testing Simulink models — use Simulink test skills
- Performance benchmarking — use profiling workflows
## Must-Follow Rules
- **Present a test plan first** — For non-trivial test suites, propose test methods and edge cases for user approval before writing code
- **Always use class-based tests** — Every test file must inherit from `matlab.unittest.TestCase`. Never use script-based tests
- **No logic in test methods** — No `if`, `switch`, `for`, or `try/catch`. Follow **Arrange-Act-Assert**. If a test needs conditionals, split into separate methods
- **Test public interfaces, not implementation** — Never test private methods directly
- **Execute via MCP** — Use `run_matlab_test_file` or `evaluate_matlab_code` to run tests
## Workflow
### Simple tests (clear behavior, limited scope)
1. Briefly state what you'll test (methods + key edge cases)
2. Write the test file after user confirms
### Standard tests (large codebase, multiple files)
1. **Gather requirements** — Code to test, expected behaviors, error conditions, scope, dependencies
2. **Present test plan** — List test methods, edge cases, parameterization strategy for approval
3. **Implement** — Write tests following the patterns below
4. **Run** — Execute via `run_matlab_test_file` MCP tool
5. **Check coverage** — Identify untested paths, add tests
## Key Functions
| Category | Functions | Purpose |
|----------|-----------|---------|
| Equality | `verifyEqual`, `verifyNotEqual` | Compare values (use `AbsTol` for floats) |
| Boolean | `verifyTrue`, `verifyFalse` | Check logical conditions |
| Size/type | `verifySize`, `verifyClass`, `verifyEmpty` | Structural checks |
| Errors | `verifyError` | Confirm error is thrown with correct ID |
| Warnings | `verifyWarning`, `verifyWarningFree` | Check warning behavior |
| Infra | `runtests`, `TestSuite`, `TestRunner` | Run and organize tests |
| Coverage | `CodeCoveragePlugin`, `CoverageResult` | Measure test coverage |
### Qualification Levels
| Level | On failure | When to use |
|-------|-----------|-------------|
| `verify` | Continues test | Default — most assertions |
| `assert` | Stops current test | Setup validation |
| `fatal` | Stops entire suite | Environment preconditions |
| `assume` | Skips test | Conditional execution (e.g., toolbox check) |
## Patterns
### Basic Test Class
```matlab
classdef computeAreaTest < matlab.unittest.TestCase
%computeAreaTest Tests for the computeArea function.
methods (Test)
function testSquare(testCase)
result = computeArea(5, 5);
testCase.verifyEqual(result, 25);
end
function testFloatingPoint(testCase)
result = computeArea(1/3, 3);
testCase.verifyEqual(result, 1, AbsTol=1e-12);
end
function testNegativeInputErrors(testCase)
testCase.verifyError( ...
@() computeArea(-1, 5), 'computeArea:negativeInput');
end
end
end
```
### Parameterized Tests
Parameterize only when assertion logic is identical across all cases — only the data varies. Use struct for readable test names:
```matlab
classdef unitConverterTest < matlab.unittest.TestCase
properties (TestParameter)
conversionCase = struct( ...
'freezing', struct('input', 0, 'expected', 32), ...
'boiling', struct('input', 100, 'expected', 212), ...
'bodyTemp', struct('input', 37, 'expected', 98.6));
end
methods (Test)
function testCelsiusToFahrenheit(testCase, conversionCase)
result = celsiusToFahrenheit(conversionCase.input);
testCase.verifyEqual(result, conversionCase.expected, AbsTol=1e-10);
end
end
end
```
For advanced parameterization (combinations, dynamic parameters, `ClassSetupParameter`), see [reference/parameterized-tests-guidance.md](reference/parameterized-tests-guidance.md).
### Setup, Teardown, and Fixtures
Prefer `addTeardown` over `TestMethodTeardown` blocks. Use `PathFixture` to add source folders:
```matlab
classdef fileProcessorTest < matlab.unittest.TestCase
methods (TestClassSetup)
function addSourceToPath(testCase)
srcFolder = fullfile(fileparts(fileparts(mfilename('fullpath'))), 'src');
testCase.applyFixture(matlab.unittest.fixtures.PathFixture(srcFolder, ...
IncludingSubfolders=true));
end
end
methods (Test)
function testProcessFile(testCase)
tmpDir = string(tempname);
mkdir(tmpDir);
testCase.addTeardown(@() rmdir(tmpDir, 's'));
testFile = fullfile(tmpDir, "data.csv");
writematrix(rand(10, 3), testFile);
result = processFile(testFile);
testCase.verifySize(result, [10 3]);
end
end
end
```
For built-in fixtures, custom fixtures, and shared fixtures, see [reference/fixtures-guidance.md](reference/fixtures-guidance.md).
### Determinism
Seed the RNG and restore it in teardown for reproducible tests:
```matlab
methods (TestMethodSetup)
function resetRandomSeed(testCase)
originalRng = rng;
testCase.addTeardown(@() rng(originalRng));
rng(42, "twister");
end
end
```
### Test Tags
Use `TestTags` for selective execution:
```matlab
methods (Test, TestTags = {'Unit'})
function testFastCalculation(testCase)
% ...>
Import recorded driving sensor data (GPS, camera, lidar, actor tracks, lanes) into scenariobuilder.* objects (GPSData, CameraData, LidarData, ActorTrackData, Trajectory, laneData) and run preprocessing — synchronize, offset correction, crop, normalizeTimestamps, convertTimestamps. Also: compute actor tracks from lidar when no annotations exist, attach camera/lidar mounting + intrinsics, export to MAT/workspace/timetable/script. Use for raw driving dataset files (KITTI, nuScenes, Waymo, Pandaset, ROS/ROS2 bags, .mat, .csv, .mp4) or driving/vehicle/sensor logs that need wrapping. drivingLogAnalyzer (DLA) is OPT-IN ONLY — invoke only on explicit user request ('DLA', 'open in DLA', 'inspect/explore/analyze the recording') or reported sensor problem (sync drift, timestamp mismatch, overlay misalignment). NEVER auto-launch DLA after wrapping (Rule 0). For 'build scenario / export to RoadRunner / drivingScenario / OpenSCENARIO / Unreal / simulate', hand off to matlab-scenario-builder.
Generate driving scenes, scenarios, road surfaces, and 3D content from already-wrapped scenariobuilder.* sensor data (GPS, camera, lidar, actor tracks) using Scenario Builder for Automated Driving Toolbox. Use to BUILD, EXPORT, or AUGMENT a virtual scenario/scene/map: ego or actor trajectories, trajectory smoothing, OpenCRG road-surface extraction, 3D asset generation, static-object placement, point-cloud georeferencing + elevation, lane-based ego localization, sensor-fusion tracking, scenario-event extraction (cut-ins, hard brakes, near-misses, ADAS disengagements), or export to RoadRunner, drivingScenario, OpenDRIVE, OpenCRG, OpenSCENARIO, or Unreal Engine. Also: log-to-scenario, scenario harvesting, accident/near-miss reconstruction, SOTIF (ISO 21448) and ISO 26262 scenario coverage, USGS-aerial-lidar scene augmentation, traffic-sign placement from camera+lidar logs. NOT for raw-data import or multi-sensor sync/crop/offset/timestamp normalization — route those to matlab-driving-data-importer.
>
>
>
>
Build, modify, and diagram SimBiology models — API reference, helper functions, and layout patterns. Use when constructing or editing models programmatically or visually.