フィルターのクリア

How to unit test a long function?

2 ビュー (過去 30 日間)
BdS
BdS 2018 年 10 月 26 日
コメント済み: Stephen23 2018 年 10 月 26 日
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:
function roots=quadraticSolver(a,b,c)
% quadraticSolver returns solutions to the
% quadratic equation a*x^2+b*x+c=0.
if ~isa(a,'numeric') || ~isa(b,'numeric') || ~isa(c,'numeric')
error('quadraticSolver:InputsMustBeNumeric',...
'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 件のコメント
Stephen23
Stephen23 2018 年 10 月 26 日
"...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.

サインインしてコメントする。

回答 (1 件)

madhan ravi
madhan ravi 2018 年 10 月 26 日
function roots=quadraticSolver(a,b,c)
% quadraticSolver returns solutions to the
% quadratic equation a*x^2+b*x+c=0.
if ~isa(a,'numeric') || ~isa(b,'numeric') || ~isa(c,'numeric')
error('quadraticSolver:InputsMustBeNumeric',...
'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
  2 件のコメント
madhan ravi
madhan ravi 2018 年 10 月 26 日
編集済み: madhan ravi 2018 年 10 月 26 日
Maybe like the above? First it verifies if condition and passes to next condition when if condition is fails.
Stephen23
Stephen23 2018 年 10 月 26 日
BdS's "Answer" moved here:
thank you for your answer. It was just an example of a function. The challenge is that in reality I've got function with 200 lines of code. I have to unit test almost all main steps in the function code.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by