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
% returns (value + 3)
% >> add3(7)
% ans =
% >> add3([2 4])
% ans =
% 5 7
if ~ isnumeric(value)
error('add3(value) requires value to be a number');
sum = value + 3;
Put that in "add3.m".
Now we can run "doctest add3", and we'll get this:
TAP version 13
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!
Thomas Smith (2022). Doctest - embed testable examples in your function's help comments (https://www.mathworks.com/matlabcentral/fileexchange/28862-doctest-embed-testable-examples-in-your-function-s-help-comments), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Platform CompatibilityWindows macOS Linux
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!