Skip to main content

Ask Steve! - A unit test framework in MATLAB?

Posted by s.crouch on 13 July 2011 - 4:09pm

You may recall a while back I looked at test-driven development, and covered unit testing. Well, I received a related question asking whether there was a unit test framework for MATLAB, so let’s have a quick look at a few of these…

Arguably the most popular is the xUnit Test Framework, which is compatible with MATLAB 7.6 (R2008a) or later. You can write unit tests using the standard MATLAB function files, or xUnit-style subclasses (like Java JUnit) and it has comprehensive documentation. There is also a very good technical article on Automated Software Testing for MATLAB which is aimed at researchers wanting to do unit testing in xUnit, complete with examples and advice. Greg Wilson from the excellent Software Carpentry project contributed to the article, and the Software Carpentry site has many general tutorials on using MATLAB.

There are others, including mlunit_2008a, which may also be worth a look, as well as the interesting Doctest for MATLAB, which works like doctest in Python – you embed simple tests into the function’s help description in the code. For example, you could specify in a MATLAB function:

function sum = subtract2(value)
% subtracts 2 from a number
%
% subtract2(value)
% returns (value - 2)
%
% Examples:
% >> subtract2(3)
% ans =
% 1
%
% >>subtract2([8 5])
% ans =
% 6 2
if ~ isnumeric(value) 
 error('subtract2(value) requires value to be a number'); 
end
sum = value - 2;

Then you can run doctest subtract2 and have those embedded tests returned:

TAP version 1.3
1.3
ok 1 - "subtract2(3)"
ok 2 - "subtract2([8 5])"

It would depend on what the nature of the tests you wish to write, and how complex, as to whether this approach is suitable.

’til next time!

Share this page

We use cookies on our website to support technical features that enhance your user experience.

We also use analytics & advertising services. To opt-out click for more information.