Main Content

createTemporaryFolder

Class: matlab.unittest.TestCase
Namespace: matlab.unittest

Create temporary folder

Since R2022a

Description

example

folder = createTemporaryFolder(testCase) creates a temporary folder for the test case and returns the full path to the folder as a character vector. The lifecycle of the folder is tied to the test case. Once the test case goes out of scope, the testing framework removes the folder.

Input Arguments

expand all

Test case, specified as a matlab.unittest.TestCase object.

Examples

expand all

Create tests that use a temporary folder to test writing to a file.

In a file in your current folder, create the WritingToFileTest class. Define two Test methods in the class that write to a file in a temporary folder and then verify the contents of the file. To create a new temporary folder for each test, call the createTemporaryFolder method within a TestMethodSetup methods block.

classdef WritingToFileTest < matlab.unittest.TestCase
    properties
        Folder
    end

    methods (TestMethodSetup)
        function setup(testCase)
            testCase.Folder = testCase.createTemporaryFolder();
        end
    end

    methods (Test)
        function test1(testCase)
            file = fullfile(testCase.Folder,"myFile.txt");
            fid = fopen(file,"w");
            testCase.addTeardown(@fclose,fid)
            testCase.assertNotEqual(fid,-1,"IO Problem")
            txt = repmat("ab",1,1000);
            dataToWrite = join(txt);
            fprintf(fid,"%s",dataToWrite);
            testCase.verifyEqual(string(fileread(file)),dataToWrite)
        end

        function test2(testCase)
            file = fullfile(testCase.Folder,"myFile.txt");
            fid = fopen(file,"w");
            testCase.addTeardown(@fclose,fid)
            testCase.assertNotEqual(fid,-1,"IO Problem")
            txt = repmat("A B",1,1000);
            dataToWrite = join(txt);
            fprintf(fid,"%s",dataToWrite);
            testCase.verifyEqual(string(fileread(file)),dataToWrite)
        end
    end
end

Run the tests. Once a test runs to completion, the testing framework automatically removes the temporary folder for that test.

runtests("WritingToFileTest")
Running WritingToFileTest
..
Done WritingToFileTest
__________
ans = 
  1×2 TestResult array with properties:

    Name
    Passed
    Failed
    Incomplete
    Duration
    Details

Totals:
   2 Passed, 0 Failed, 0 Incomplete.
   1.3432 seconds testing time.

Tips

  • The matlab.unittest.fixtures.TemporaryFolderFixture class provides a fixture to create a temporary folder. More functionality is available when you create a temporary folder using the fixture. For example, you can specify a suffix for the temporary folder name.

Version History

Introduced in R2022a