Code covered by the BSD License  

Highlights from
Doctest - embed testable examples in your function's help comments

Be the first to rate this file! 10 Downloads (last 30 days) File Size: 18.02 KB File ID: #28862

Doctest - embed testable examples in your function's help comments

by Thomas Smith

 

27 Sep 2010 (Updated 28 Sep 2010)

Put a usage example in the help of your function, then test it to make sure it still works over time

| Watch this File

File Information
Description

Unit testing is great, but it can seem like overkill to make a whole new file for every test you want to run. Doctest allows you to embed tests in the documentation of your function (or class or method), so that they're in the same file as the code they test. They can also be valuable demonstrations of how to call your code.

Say you have a function that adds 3 to any numbers you give it. Let's add a doctest:

function sum = add3(value)
% adds 3 to a number
%
% add3(value)
% returns (value + 3)
%
% Examples:
%
% >> add3(7)
%
% ans =
%
% 10
%
% >> add3([2 4])
%
% ans =
%
% 5 7
if ~ isnumeric(value)
    error('add3(value) requires value to be a number');
end

sum = value + 3;

Put that in "add3.m".
Now we can run "doctest add3", and we'll get this:

TAP version 13
1..3
ok 1 - "add3(7)"
ok 2 - "add3([2 4])"

This tells you that your examples work correctly. Now, if you accidentally change the function so that it adds 10^30 instead of 3, the next time you run your tests you'll quickly find the problem. Yay testing!

Other features --- wildcard support for output that *should* change --- test functions, classes, and methods --- handles exceptions, see if you correctly catch an error --- uses a standard output format ( http://testanything.org/ ) --- easy to write examples, just cut+paste from command window

This function is inspired by the Python doctest module: http://docs.python.org/library/doctest.html

The newest version can always be obtained at http://bitbucket.org/tgs/doctest-for-matlab/src , where there is also a bug tracker if you have any issues. Contributions are also welcome!

Acknowledgements

The author wishes to acknowledge the following in the creation of this submission:
MUnit: a unit testing framework in Matlab, mlunit_2008a, MATLAB xUnit Test Framework

MATLAB release MATLAB 7.10 (2010a)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Please login to add a comment or rating.
Updates
28 Sep 2010

Added a note that the bug tracker is available, and invited to contribute

Tag Activity for this File
Tag Applied By Date/Time
development Thomas Smith 28 Sep 2010 11:25:16
documentation Thomas Smith 28 Sep 2010 11:25:16
test Thomas Smith 28 Sep 2010 11:25:16
testing Thomas Smith 28 Sep 2010 11:25:16
utilities Thomas Smith 28 Sep 2010 11:25:16
tools Thomas Smith 28 Sep 2010 11:25:16
unit test Thomas Smith 28 Sep 2010 11:25:16
documentation Thomas Guillod 13 Sep 2011 07:13:26

Contact us at files@mathworks.com