Main Content

本页翻译不是最新的。点击此处可查看最新英文版本。

matlab.unittest.TestSuite.fromName

类: matlab.unittest.TestSuite
命名空间: matlab.unittest

基于单个测试名称创建测试套件

说明

示例

suite = matlab.unittest.TestSuite.fromName(testName) 可基于指定的测试名称创建由单个 Test 对象组成的测试套件。

当您创建和运行标量测试套件时,由 testName 指定的测试类、函数或脚本必须在路径中。

suite = matlab.unittest.TestSuite.fromName(testName,Name,Value) 使用一个或多个名称-值参量指定选项。例如,suite = matlab.unittest.TestSuite.fromName(testName,"ExternalParameters",param) 使用指定的外部参数来创建一个标量测试套件。

输入参数

全部展开

测试名称,指定为字符串标量或字符向量。对于一个给定的测试文件,测试的名称唯一地标识测试内容的最小可运行部分。测试名称包括包名称、文件名(不包括扩展名)、过程名称和关于参数化的信息。

testName 参量与 Test 对象的 Name 属性对应。

名称-值参数

将可选的参量对组指定为 Name1=Value1,...,NameN=ValueN,其中 Name 是参量名称,Value 是对应的值。名称-值参量必须出现在其他参量之后,但参量对组的顺序无关紧要。

示例: suite = matlab.unittest.TestSuite.fromName(testName,ExternalParameters=param)

在 R2021a 之前,使用逗号分隔每个名称和值,并用引号将 Name 引起来。

示例: suite = matlab.unittest.TestSuite.fromName(testName,"ExternalParameters",param)

要在测试中使用的外部参数,指定为由 matlab.unittest.parameters.Parameter 对象组成的数组。使用此参量指定外部参数,而不是参数化测试中的现有参数。有关详细信息,请参阅在参数化测试中使用外部参数

测试所需的源文件和文件夹的名称,指定为字符串向量、字符向量或字符向量元胞向量。使用此参量时,定义测试的文件必须依赖指定的源代码。否则,该方法返回空测试套件。

指定的源代码必须表示至少一个具有 .m.p.mlx.mlapp.mat.slx 扩展名的现有文件。无法用不支持的扩展名指定文件名。如果指定文件夹名称,框架会通过提取文件夹中受支持文件的路径来展开它。

您必须有 MATLAB® Test™ 许可证才能使用 DependsOn。有关通过源代码依存关系选择测试的详细信息,请参阅 matlabtest.selectors.DependsOn (MATLAB Test)

示例: ["myFile.m" "myFolder"]

示例: ["folderA" "C:\work\folderB"]

属性

Statictrue

要了解方法的属性,请参阅方法属性

示例

全部展开

使用 fromName 静态方法基于测试名称创建标量测试套件。

在当前文件夹的一个文件中创建 add5 函数。该函数接受数值输入,并将其增加 5。如果使用非数值输入调用该函数,该函数将引发错误。

function y = add5(x)
% add5 - Increment input by 5
if ~isa(x,"numeric")
    error("add5:InputMustBeNumeric","Input must be numeric.")
end
y = x + 5;
end

要测试 add5 函数,请在当前文件夹内名为 Add5Test.m 的文件中创建 Add5Test 类。该类针对数值和非数值输入测试函数。

classdef Add5Test < matlab.unittest.TestCase
    properties (TestParameter)
        type = {'double','single','int8','int32'};
    end

    methods (Test)
        function numericInput(testCase,type)
            actual = add5(cast(1,type));
            testCase.verifyClass(actual,type)
        end
        function nonnumericInput(testCase)
            testCase.verifyError(@() add5("0"),"add5:InputMustBeNumeric")
        end
    end
end

导入 TestSuite 类。

import matlab.unittest.TestSuite

基于 Add5Test 类创建一个测试套件,并显示测试名称。

suite = testsuite("Add5Test");
disp({suite.Name}')
    {'Add5Test/numericInput(type=double)'}
    {'Add5Test/numericInput(type=single)'}
    {'Add5Test/numericInput(type=int8)'  }
    {'Add5Test/numericInput(type=int32)' }
    {'Add5Test/nonnumericInput'          }

基于对应于 nonnumericInput 方法的测试名称创建一个测试套件。生成的测试套件包含单个 Test 对象。然后,运行测试。

suite1 = TestSuite.fromName("Add5Test/nonnumericInput");
result1 = run(suite1);
Running Add5Test
.
Done Add5Test
__________

基于参数化测试的名称创建一个标量测试套件,并运行该测试。

suite2 = TestSuite.fromName("Add5Test/numericInput(type=single)");
result2 = run(suite2);
Running Add5Test
.
Done Add5Test
__________

版本历史记录

在 R2014a 中推出

全部展开