## How to unit test a long function?

### BdS (view profile)

on 26 Oct 2018
Latest activity Commented on by Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 26 Oct 2018
I have got a long function, which downloads financial data from bloombberg, aggregates, cleans it etc. Now I will have to unit test it. Do I have to create a new function for each main section of the function and then test unit them separetely or does Matlab provide a faster/more elegant method of unit test long functions? Let's show you an example. Let's imagine I have to unit test this function:
% quadraticSolver returns solutions to the
if ~isa(a,'numeric') || ~isa(b,'numeric') || ~isa(c,'numeric')
'Coefficients must be...numeric.');
end
roots(1)=(-b+sqrt(b^2-4*a*c)) /(2*a);
roots(2)=(-b-sqrt(b^2-4*a*c)) /(2*a);
end
How to test it in pieces. First the if... part and second the root(x) part. Thank you in advance for your answers.

#### 1 Comment

Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 26 Oct 2018
"...or does Matlab provide a faster/more elegant method of unit test long functions?"
Not as far as I am aware. Usually to automate function testing I have simply created a large set of test cases for the function, and carefully crafted a test script/function that checks each of them. If you really want unit testing, then you could break up your "long function" into lots of smaller functions, and test each one separately. You might even be able to include the test code in the same Mfile/s. Or, as an alternative, perhaps writing a class might make this easier.

### Tags

on 26 Oct 2018

% quadraticSolver returns solutions to the
if ~isa(a,'numeric') || ~isa(b,'numeric') || ~isa(c,'numeric')
'Coefficients must be...numeric.');
else
roots(1)=(-b+sqrt(b^2-4*a*c)) /(2*a);
roots(2)=(-b-sqrt(b^2-4*a*c)) /(2*a);
end
end