Write a test to verify that two Fibonacci sequence generation functions produce the same output. To run each function in your test, apply a fixture that makes the function available on the path.
Create a folder named fibonacci_i in your current folder. Then, in a file named sequence.m in the fibonacci_i folder, create a function that iteratively calculates the first n numbers of the Fibonacci sequence.
function s = sequence(n)
arguments
n (1,1) {mustBeInteger,mustBePositive}
end
s = zeros(1,n);
for i = 1:n
if i == 1
s(i) = 0;
elseif i == 2
s(i) = 1;
else
s(i) = s(i-1) + s(i-2);
end
end
end
Create another folder named fibonacci_r in your current folder. Then, in a file named sequence.m in the fibonacci_r folder, create a function that recursively calculates the first n numbers of the Fibonacci sequence.
function s = sequence(n)
arguments
n (1,1) {mustBeInteger,mustBePositive}
end
s = zeros(1,n);
for i = 1:n
s(i) = fib(i);
end
end
function f = fib(n)
if n == 1
f = 0;
elseif n == 2
f = 1;
else
f = fib(n-1) + fib(n-2);
end
end
In a file named SequenceTest.m in your current folder, create the SequenceTest test class that compares the functions in the fibonacci_i and fibonacci_r folders. Running each function requires the folder containing the function to be on the path. In this example, the Test method uses matlab.unittest.fixtures.PathFixture instances to access the functions under test. Each call to the applyAndRun method:
Makes one of the functions available on the path by setting up a PathFixture instance
Runs the function and returns its output
Restores the path to its original state by tearing down the fixture
classdef SequenceTest < matlab.unittest.TestCase
methods (Test)
function testSequence(testCase)
import matlab.unittest.fixtures.PathFixture
% Iterative implementation
f1 = PathFixture("fibonacci_i");
output1 = f1.applyAndRun(@() sequence(10));
% Recursive implementation
f2 = PathFixture("fibonacci_r");
output2 = f2.applyAndRun(@() sequence(10));
testCase.verifyEqual(output1,output2)
end
end
end
Run the test in the SequenceTest test class. The test passes because both implementations of the sequence function return the same output.
Running SequenceTest
.
Done SequenceTest
__________
result =
TestResult with properties:
Name: 'SequenceTest/testSequence'
Passed: 1
Failed: 0
Incomplete: 0
Duration: 2.1351
Details: [1×1 struct]
Totals:
1 Passed, 0 Failed, 0 Incomplete.
2.1351 seconds testing time.