MATLAB: Data driven Unit Tests

MATLABooptesttestcaseunitunittestsxunit

Is there a way to have data driven unit tests using the unit test framework in MATLAB? I have a TestCase class that is set up to test let say a single file.
I would then like to repeat that TestCase with all the methods on several files. I know I can make many copies of the test and set a property in the class that points to a file. But now I have several TestCase files that have exactly the same code with the only difference is a property that points to a different file.
Ideally I would like to have a list of something like files or values for a property and re-run the tests for each item in the list.
Thanks.

Best Answer

Hi Stephen,
You may be able to achieve this using a common test as a base class that has an Abstract property or an abstract method. It might look like so:
In FileTest.m
classdef FileTest < matlab.unittest.TestCase
properties(Abstract)
File
end
methods(Abstract)
data = produceRequiredData(testCase)
end
methods(Test)
function testOne(testCase)
file = testCase.File;
success = operateOnFile(file);
testCase.verifyTrue(success);
end
function testTwo(testCase)
data = testCase.produceRequiredData();
success = operateOnData(data);
testCase.verifyTrue(success);
end
end
end
Then you can quickly implement several subclasses for each of these files/data without duplicating the test content. Two such subclasses might look like:
In FirstFileTest.m:
classdef FirstFileTest < FileTest
properties
File = 'some/path/to/data/file.foo';
end
methods
function data = produceRequiredData(~)
data = generateDataOneWay;
end
end
end
SecondFileTest.m
classdef SecondFileTest < FileTest
properties
File = 'some/path/to/another/data/file.bar';
end
methods
function data = produceRequiredData(~)
data = generateDataAnotherWay;
end
end
end
Note that for both of these tests they do in fact each contain the test methods defined in the base class. Also, the FileTest class is not an executable test itself because of its abstract property and method, so it is not picked up to run as a test. However, all of its concrete subclasses are. Using this approach you can even add specific Test methods to individual test subclasses if these classes need some testing specific to the subclass.
Hope that helps!
Andy