Main Content

Create Basic Custom Fixture

This example shows how to create a basic custom fixture that changes the display format to hexadecimal representation. The example also shows how to use the fixture to test a function that displays a column of numbers as text. After the testing completes, the framework restores the display format to its pretest state.

Create FormatHexFixture Class Definition

In a file in your working folder, create a new class, FormatHexFixture that inherits from the matlab.unittest.fixtures.Fixture class. Since we want the fixture to restore the pretest state of the MATLAB® display format, create an OriginalFormat property to keep track of the original display format.

classdef FormatHexFixture < matlab.unittest.fixtures.Fixture
    properties (Access = private)
        OriginalFormat
    end
end

Implement setup and teardown Methods

Subclasses of the Fixture class must implement the setup method. Use this method to record the pretest display format, and set the format to 'hex'. Use the teardown method to restore the original display format. Define the setup and teardown methods in the methods block of the FormatHexFixture class.

classdef FormatHexFixture < matlab.unittest.fixtures.Fixture
    properties (Access = private)
        OriginalFormat
    end
    methods
        function setup(fixture)
            fixture.OriginalFormat = format;
            format hex
        end
        function teardown(fixture)
            format(fixture.OriginalFormat)
        end
    end
end

Apply Custom Fixture

In a file in your working folder, create the following test class, SampleTest.m.

classdef SampleTest < matlab.unittest.TestCase
    methods (Test)
        function test1(testCase)
            testCase.applyFixture(FormatHexFixture)
            actStr = getColumnForDisplay([1;2;3],'Small Integers');
            expStr = ['Small Integers  '
                '3ff0000000000000'
                '4000000000000000'
                '4008000000000000'];
            testCase.verifyEqual(actStr,expStr)
        end
    end
end

function str = getColumnForDisplay(values,title)
elements = cell(numel(values)+1,1);
elements{1} = title;
for idx = 1:numel(values)
    elements{idx+1} = displayNumber(values(idx));
end
str = char(elements);
end

function str = displayNumber(n)
str = strtrim(evalc('disp(n);'));
end

This test applies the custom fixture and verifies that the displayed column of hexadecimal representation is as expected.

At the command prompt, run the test.

run(SampleTest);
Running SampleTest
.
Done SampleTest
__________

See Also

Related Topics