Create Tests for MATLAB Source Code - MATLAB & Simulink - MathWorks United Kingdom (2024)

Create Tests for MATLAB Source Code

MATLAB® Test™ enables you to interactively create tests for your scripts and functions in the Editor or Live Editor. The test file created for a script or function contains a test class to exercise that script or function. You can use this file as a starting point for writing your own tests.

This topic shows how to create a test for a simple function and then build on the generated test code.

Create Test for Function

In a file named quadraticSolver.m in your current folder, create the quadraticSolver function. The function takes as inputs the coefficients of a quadratic polynomial and returns the roots of that polynomial. To validate its inputs, the function uses an arguments block.

function r = quadraticSolver(a,b,c)% quadraticSolver returns solutions to the% quadratic equation a*x^2 + b*x + c = 0.arguments a {mustBeNumeric,mustBeNonzero} b {mustBeNumeric} c {mustBeNumeric}endr = sort([(-b + sqrt(b^2 - 4*a*c)) / (2*a); ... (-b - sqrt(b^2 - 4*a*c)) / (2*a)]);end

To create a test file that contains initial test code for the quadraticSolver function, right-click in the Editor and select Create Test.

Create Tests for MATLAB Source Code- MATLAB & Simulink- MathWorks United Kingdom (1)

This code provides the contents of the resulting test file. The generated test class:

  • Includes autogenerated inputs that satisfy the arguments block in the quadraticSolver function

  • Calls the quadraticSolver function to produce an output

  • Uses the verifyEqual qualification method to test the produced output

% This is an autogenerated sample test for file quadraticSolver.mclassdef testquadraticSolver < matlab.unittest.TestCase methods (Test) function test_quadraticSolver(testCase) a = -7162.2732; b = -1564.7743; c = 8314.7105; % Specify the expected output(s) of % quadraticSolver expected_r = ; % Exercise the function quadraticSolver actual_r = quadraticSolver(a, b, c); testCase.verifyEqual(actual_r, expected_r); end endend

A test file created for your script or function serves only as a starting point. For example, you must at least specify the expected output in the test code generated for the quadraticSolver function before running the test.

Note

MATLAB Test attempts to generate input argument values only if your function uses an arguments block for input argument validation. If your function does not include an arguments block, then the test class does not include autogenerated data to represent the input arguments.

Build on Generated Test Code

Build on the test code generated for the quadraticSolver function by first completing the code of the generated Test method and then adding another Test method using the code insertion options on the toolstrip. For more information on how to interactively add elements to a test class, see Insert Test Code Using Editor.

Complete Generated Test Method

The generated test for the quadraticSolver function requires you to specify the expected output of the function. To complete the test and make it more readable, follow these steps:

  1. Rename the test class as SolverTest and the Test method as solution. Then, remove the comments you no longer need from the file and save the file as SolverTest.m in your current folder.

  2. Specify the expected output of the function by calling the roots function with the autogenerated values.

  3. Because the verifyEqual method tests floating-point vectors, specify a tolerance for comparison.

classdef SolverTest < matlab.unittest.TestCase methods (Test) function solution(testCase) a = -7162.2732; b = -1564.7743; c = 8314.7105; expected_r = sort(roots([a b c])); actual_r = quadraticSolver(a,b,c); testCase.verifyEqual(actual_r,expected_r,AbsTol=eps) end endend

Add Another Test Method

To test the quadraticSolver function against invalid inputs, add another Test method to the class by clicking Create Tests for MATLAB Source Code- MATLAB & Simulink- MathWorks United Kingdom (2) in the Test section on the Editor tab.

Create Tests for MATLAB Source Code- MATLAB & Simulink- MathWorks United Kingdom (3)

Implement the added method by following these steps:

  1. Rename the method as nonnumericInput.

  2. Add code to the method to verify that the quadraticSolver function throws an error when it is called with inputs 1, '-3', and 2.

Save the file. This code provides the contents of the SolverTest class.

classdef SolverTest < matlab.unittest.TestCase methods (Test) function solution(testCase) a = -7162.2732; b = -1564.7743; c = 8314.7105; expected_r = sort(roots([a b c])); actual_r = quadraticSolver(a,b,c); testCase.verifyEqual(actual_r,expected_r,AbsTol=eps) end function nonnumericInput(testCase) testCase.verifyError(@()quadraticSolver(1,'-3',2), ... "MATLAB:validators:mustBeNumeric") end endend

Run Tests in Test Class

You can run the tests in the SolverTest class interactively in the Editor or in the Test Browser app. For example, with the test class code visible in the Editor, go to the Editor tab and in the Run section, click Create Tests for MATLAB Source Code- MATLAB & Simulink- MathWorks United Kingdom (4). In this example, both the tests pass.

Create Tests for MATLAB Source Code- MATLAB & Simulink- MathWorks United Kingdom (5)

For more information on how to run tests and customize your test run interactively, see Run Tests in Editor and Run Tests Using Test Browser.

See Also

Functions

  • verifyEqual

Classes

  • matlab.unittest.TestCase

Related Topics

  • Insert Test Code Using Editor
  • Function Argument Validation
Create Tests for MATLAB Source Code
- MATLAB & Simulink
- MathWorks United Kingdom (2024)

FAQs

How do I test my MATLAB code? ›

You can use the code analyzer to check your code interactively in the MATLAB® Editor while you work. To verify that continuous code checking is enabled: In MATLAB, select the Home tab and then click Preferences. In the Preferences dialog box, select Code Analyzer.

How to run unit test in MATLAB? ›

To run tests with the Unit Test framework:
  1. Create a TestSuite from the Simulink Test file.
  2. Create a TestRunner .
  3. Create plugin objects to customize the TestRunner . For example: The matlab. ...
  4. Add the plugins to the TestRunner .
  5. Run the test using the run method, or run tests in parallel using the runInParallel method.

What is a MATLAB test? ›

MATLAB® Test™ provides tools for developing, executing, measuring, and managing dynamic tests of MATLAB code, including deployed applications and user-authored toolboxes. You can use the project-based quality dashboard to raise the visibility of code readiness to an intuitive summary level.

How to test Simulink models? ›

Use the Test Manager to create real-time test cases.
  1. In the Simulink toolstrip, on the Apps tab under Model Verification, Validation, and Test, select Simulink Test.
  2. Click Simulink Test Manager.
  3. In the Test Manager, select New > Test Case > Real-Time Test.

How to check source code in MATLAB? ›

For most Matlab functions you can see the source code by typing "edit <function_name>" at the Matlab prompt. Yet most of the basic function are internally implemented and you won't be able to see the source code.

How to open Simulink test in MATLAB? ›

Use one of these options to open the Simulink Test Manager:
  1. In the Simulink toolstrip. Open the Apps tab. In the Model Verification, Validation, and Test section, click Simulink Test. On the Tests tab, click Simulink Test Manager on the Tests toolstrip.
  2. At the MATLAB command prompt, enter sltest. testmanager. view .

How to test a function in MATLAB? ›

When you run function-based tests, the testing framework executes these tasks:
  1. Create an array of tests specified by local test functions.
  2. If the setupOnce function is specified, set up the pretest state of the system by running the function.
  3. For each test, run the corresponding local test function.

What is Simulink check in MATLAB? ›

Simulink Check analyzes your models, requirements, and tests to assess design quality and compliance with standards. It provides industry-recognized checks and metrics that identify modeling standard and guideline violations as you design.

How do I run a test file in MATLAB? ›

Right-click a test file in the Current Folder browser and then select Run. Open a test file in the MATLAB Editor or Live Editor and then run the tests using the Run section in the Editor or Live Editor tab of the toolstrip.

Can MATLAB detect cheating? ›

MATLAB Grader does not contain a built-in solution for actively monitoring submissions and preventing cheating. However, for courses run on the MATLAB Grader platform, instructors do have access to all submissions made for a problem. Student submissions can be downloaded and analyzed in the instructor's preferred tool.

How do I run my MATLAB code? ›

On the Editor or Live Editor tab, in the Run section, click Run. Run the code in the selected section.

How to check MATLAB function code? ›

Check MATLAB Function Using Code Analyzer
  1. In MATLAB, select the Home tab and then click Preferences.
  2. In the Preferences dialog box, select Code Analyzer.
  3. In the MATLAB Code Analyzer Preferences pane, verify that Enable integrated warning and error messages is selected.

How to verify code in MATLAB? ›

Use software-in-the-loop (SIL) and processor-in-the-loop (PIL) execution to check the numerical behavior of the code that you generate from MATLAB functions. A software-in-the-loop (SIL) execution compiles generated source code and executes the code as a separate process on your development computer.

Top Articles
Fort Worth Star-Telegram from Fort Worth, Texas
Low Blood Sugar Sleepy - Diabetes Medications - Société Française De Pharmacie Oncologique
Spasa Parish
The Machine 2023 Showtimes Near Habersham Hills Cinemas
Gilbert Public Schools Infinite Campus
Rentals for rent in Maastricht
159R Bus Schedule Pdf
11 Best Sites Like The Chive For Funny Pictures and Memes
Finger Lakes 1 Police Beat
Craigslist Pets Huntsville Alabama
Paulette Goddard | American Actress, Modern Times, Charlie Chaplin
Red Dead Redemption 2 Legendary Fish Locations Guide (“A Fisher of Fish”)
What's the Difference Between Halal and Haram Meat & Food?
Rugged Gentleman Barber Shop Martinsburg Wv
Jennifer Lenzini Leaving Ktiv
Havasu Lake residents boiling over water quality as EPA assumes oversight
Justified - Streams, Episodenguide und News zur Serie
Epay. Medstarhealth.org
Olde Kegg Bar & Grill Portage Menu
Half Inning In Which The Home Team Bats Crossword
Amazing Lash Bay Colony
Cato's Dozen Crossword
Cyclefish 2023
What’s Closing at Disney World? A Complete Guide
New from Simply So Good - Cherry Apricot Slab Pie
Ohio State Football Wiki
Find Words Containing Specific Letters | WordFinder®
FirstLight Power to Acquire Leading Canadian Renewable Operator and Developer Hydromega Services Inc. - FirstLight
Webmail.unt.edu
When Is Moonset Tonight
Metro By T Mobile Sign In
Restored Republic December 1 2022
Dl 646
Apple Watch 9 vs. 10 im Vergleich: Unterschiede & Neuerungen
12 30 Pacific Time
Operation Carpe Noctem
Nail Supply Glamour Lake June
Anmed My Chart Login
No Compromise in Maneuverability and Effectiveness
'I want to be the oldest Miss Universe winner - at 31'
Gun Mayhem Watchdocumentaries
Ice Hockey Dboard
Infinity Pool Showtimes Near Maya Cinemas Bakersfield
Dermpathdiagnostics Com Pay Invoice
A look back at the history of the Capital One Tower
Alvin Isd Ixl
Maria Butina Bikini
Busted Newspaper Zapata Tx
Rubrankings Austin
2045 Union Ave SE, Grand Rapids, MI 49507 | Estately 🧡 | MLS# 24048395
Upgrading Fedora Linux to a New Release
Latest Posts
Article information

Author: Tuan Roob DDS

Last Updated:

Views: 6109

Rating: 4.1 / 5 (42 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Tuan Roob DDS

Birthday: 1999-11-20

Address: Suite 592 642 Pfannerstill Island, South Keila, LA 74970-3076

Phone: +9617721773649

Job: Marketing Producer

Hobby: Skydiving, Flag Football, Knitting, Running, Lego building, Hunting, Juggling

Introduction: My name is Tuan Roob DDS, I am a friendly, good, energetic, faithful, fantastic, gentle, enchanting person who loves writing and wants to share my knowledge and understanding with you.