MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1
these variables. However, in subsequent tests, the value is reset to the value defined in
the shared variables section.


  • In the shared variables section (first code section), define any preconditions necessary
    for your tests. If the inputs or outputs do not meet this precondition, MATLAB does not
    run any of the tests. MATLAB marks the tests as failed and incomplete.

  • When a script is run as a test, variables defined in one test are not accessible within
    other tests unless they are defined in the shared variables section (first code section).
    Similarly, variables defined in other workspaces are not accessible to the tests.

  • If the script file does not include any code sections, MATLAB generates a single test
    element from the full contents of the script file. The name of the test element is the
    same as the script file name. In this case, if MATLAB encounters a failed test, it halts
    execution of the entire script.


In rightTriTest.m, write four tests to test the output of rightTri. Use the assert
function to test the different conditions. In the shared variables section, define four
triangle geometries and define a precondition that the rightTri function returns a right
triangle.


% test triangles
tri = [7 9];
triIso = [4 4];
tri306090 = [2 2*sqrt(3)];
triSkewed = [1 1500];


% preconditions
angles = rightTri(tri);
assert(angles(3) == 90,'Fundamental problem: rightTri not producing right triangle')


%% Test 1: sum of angles
angles = rightTri(tri);
assert(sum(angles) == 180)


angles = rightTri(triIso);
assert(sum(angles) == 180)


angles = rightTri(tri306090);
assert(sum(angles) == 180)


angles = rightTri(triSkewed);
assert(sum(angles) == 180)


Write Script-Based Unit Tests
Free download pdf