matlab.unittest.TestCase.createTemporaryFolder - Create temporary folder - MATLAB (original) (raw)

Main Content

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

Create temporary folder

Since R2022a

Syntax

Description

folder = createTemporaryFolder([testCase](#mw%5F625f9671-aaf5-4389-8187-a4a7c3838c17)) 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.

example

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

Version History

Introduced in R2022a