Andi
Andi

Reputation: 4865

Import package in MATLAB unit test

I'd like to import a package within a MATLAB unit test. I need to instantiate objects from this package in quite a number of test methods, so I thought the import function is best placed within the TestClassSetup method. So, my code looks like this:

methods (TestClassSetup)
    function load_mockupMatrix(testCase)
        import('technicalIndicators.*');
        testCase.data = tests.createMockupMatrix;
    end
end

Apparently, the technicalIndicators package is not available within individual test methods. My guess is that this has something to do with the scope of the import function.

Now, how and where in the code am I supposed to use the import function in order to be able to use this package in individual test methods?

Upvotes: 2

Views: 202

Answers (1)

Suever
Suever

Reputation: 65450

The import command only affects the import list of the function within which it is used. Since each method of a class has a different workspace, an import call in the setup method will have no effect in any of the actual tests.

There are a few options for how to do this.

One would be to place your import statement within each test method

methods (Test)
    function myFirstTest(testCase)
        import('technicalIndicators.*');
        % Do stuff
    end
end

The other is that you could potentially create a property of your TestCase subclass that contains a function handle to the constructor of the desired class (which you could assign during your TestClassSetup). This would essentially give you a "shortcut" to the class rather than explicitly importing it within every method instantiating with it's fully-qualified name every time.

classdef MyTest < matlab.unittest.TestCase

    properties
        TechnicalIndicator1
        TechnicalIndicator2
    end

    methods (TestClassSetup)
        function import_stuff(testCase)
            import technicalIndicators.*
            testCase.TechnicalIndicator1 = @TechnicalIndicator1;
            testCase.TechnicalIndicator2 = @TechnicalIndicator2;
        end
    end

    methods (Test)
        function MySecondTest(testCase)
            thing = testCase.TechnicalIndicator1();
            % Do test
        end
    end
end

In general, it is also recommended to import specific classes and functions explicitly rather than using the .* notation to prevent possible name conflicts.

Upvotes: 1

Related Questions