MATLAB xUnit Test Framework: How to Write xUnit-Style Tests by Subclassing TestCase
The MATLAB xUnit architecture is based closely on the xUnit style, in which each test case is an instance of a subclass of the base TestCase class. Programmers who are familiar with this style may want to write their own TestCase subclasses instead of using subfunction-based tests.
This example shows a TestCase subclass containing test case methods and test fixture methods. If you are not familiar with defining your own classes in MATLAB, you might want to review the MATLAB documentation on classes and object-oriented programming, or you can simply stick to using subfunction-based tests.
The sample M-file begins with the classdef statement, which sets the name of the class and indicates that it is a subclass of TestCase.
cd examples_general dbtype TestUsingTestCase 1
1 classdef TestUsingTestCase < TestCase
The properties block contains a field that is initialized by the setup method and is used by the two test methods.
dbtype TestUsingTestCase 3:5
3 properties 4 fh 5 end
The first method in the methods block is the constructor. It takes the desired test method name as its input argument, and it passes that input along to the base class constructor.
dbtype TestUsingTestCase 7:10
7 methods 8 function self = TestUsingTestCase(name) 9 self = self@TestCase(name); 10 end
The setUp method creates a figure window and stores its handle in the field fh.
dbtype TestUsingTestCase 12:14
12 function setUp(self) 13 self.fh = figure; 14 end
Test methods are those beginning with "test".
dbtype TestUsingTestCase 20:26
20 function testColormapColumns(self) 21 assertEqual(size(get(self.fh, 'Colormap'), 2), 3); 22 end 23 24 function testPointer(self) 25 assertEqual(get(self.fh, 'Pointer'), 'arrow'); 26 end
The tearDown method cleans up by deleting the figure window.
dbtype TestUsingTestCase 16:18
16 function tearDown(self) 17 delete(self.fh); 18 end
Run the test cases in the class by calling runxunit with the name of the class.
runxunit TestUsingTestCase
Test suite: TestUsingTestCase Test suite location: C:\Users\psexton\Documents\GitHub\matlab-xunit-doctest\doc\examples_general\TestUsingTestCase.m 20-Feb-2014 19:59:09 Starting test run with 2 test cases. .. PASSED in 0.123 seconds.