MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Write Test Using Live Script


This example shows how to test a function that you create by writing a live script,
'TestRightTriLiveScriptExample.mlx'. The example function computes the angles
of a right triangle, and you create a live-script-based unit test to test the function.

A live-script-based test must adhere to the following conventions:


  • The name of the live-script file must start or end with the word 'test', which is case-
    insensitive.

  • Place each unit test into a separate section of the live-script file. The heading of each
    section becomes the name of the test element. If a section has no heading, MATLAB
    assigns a name to the test.

  • Consider how you are running your live-script-based test. If you run the test using the
    Run buttons in the Live Editor and MATLAB encounters a test failure, then it stops
    execution of the script and does not run any remaining tests. If you run the live script
    using the unit testing framework, such as with the runtests function, then if
    MATLAB encounters a test failure, it still runs remaining tests.

  • When a live script runs as a test, variables defined in one test are not accessible within
    other tests. Similarly, variables defined in other workspaces are not accessible to the
    tests.


Outside of this example, in your current MATLAB folder, create a function in a file,
rightTri.m. This function takes lengths of two sides of a triangle as input and returns
the three angles of the corresponding right triangle. The input sides are the two shorter
edges of the triangle, not the hypotenuse.

type rightTri.m

function angles = rightTri(sides)

A = atand(sides(1)/sides(2));
B = atand(sides(2)/sides(1));
hypotenuse = sides(1)/sind(A);
C = asind(hypotenuse*sind(A)/sides(1));

angles = [A B C];

end

Write Test Using Live Script
Free download pdf