MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1
To provide diagnostic information (Error Details) that is more informative than
'Assertion failed' (Test 3), consider passing a message to the assert function (as
in Test 4). Or you can also consider using function-based unit tests.

Revise Test to Use Tolerance

Save rightTriTest.m as rightTriTolTest.m, and revise Test 3 and Test 4 to use a
tolerance. In Test 3 and Test 4, instead of asserting that the angles are equal to an
expected value, assert that the difference between the actual and expected values is less
than or equal to a specified tolerance. Define the tolerance in the shared variables section
of the test script so it is accessible to both tests.

For script-based unit tests, manually verify that the difference between two values is less
than a specified tolerance. If instead you write a function-based unit test, you can access
built-in constraints to specify a tolerance when comparing floating-point values.

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

% Define an absolute tolerance
tol = 1e-10;

% 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)

%% Test 2: isosceles triangles

33 Unit Testing

Free download pdf