MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Write Script-Based Unit Tests


This example shows how to write a script that tests a function that you create. The
example function computes the angles of a right triangle, and you create a script-based
unit test to test the function.

Create rightTri Function to Test

Create this function in a file, rightTri.m, in your current MATLAB® folder. 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.

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

Create Test Script

In your working folder, create a new script, rightTriTest.m. Each unit test checks a
different output of the rightTri function. A test script must adhere to the following
conventions:


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

  • Place each unit test into a separate section of the script file. Each section begins with
    two percent signs (%%), and the text that follows on the same line becomes the name of
    the test element. If no text follows the %%, MATLAB assigns a name to the test. If
    MATLAB encounters a test failure, it still runs remaining tests.

  • In a test script, the shared variable section consists of any code that appears before
    the first explicit code section (the first line beginning with %%). Tests share the
    variables that you define in this section. Within a test, you can modify the values of


33 Unit Testing

Free download pdf