You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MATLAB单元测试框架中为测试结果及报告添加测试描述

MATLAB单元测试:提取方法注释作为测试描述并同步到报告

要实现将测试方法的注释作为测试描述,同步到测试结果表格和HTML报告中,可按以下步骤操作:

1. 改造测试类,自动提取注释为测试描述

在测试类中添加辅助函数解析方法注释,并通过TestMethodSetup在每个测试执行前自动设置描述:

classdef myClass < matlab.unittest.TestCase
    methods (Test)
        function addAandB(testCase)
            % 测试两个整数的加法运算,验证结果是否符合预期
            a = 2; b = 3;
            testCase.verifyEqual(a+b, 5);
        end
        
        function multiplyXandY(testCase)
            % 测试两个浮点数的乘法运算,处理边界值
            x = 0.5; y = 4;
            testCase.verifyEqual(x*y, 2);
        end
    end
    
    % 辅助函数:提取指定方法的注释文本
    methods (Access = private)
        function desc = getTestMethodDescription(testCase, methodName)
            metaClass = meta.class.fromName(class(testCase));
            targetMethod = metaClass.MethodList(strcmp({metaClass.MethodList.Name}, methodName));
            desc = targetMethod.Description;
            % 清理注释格式:替换换行为空格,去除首尾空格
            desc = strtrim(regexprep(desc, '\n+', ' '));
        end
    end
    
    % 每个测试方法执行前自动设置描述
    methods (TestMethodSetup)
        function setupTestDescription(testCase)
            currentMethod = testCase.TestName;
            testCase.Description = testCase.getTestMethodDescription(currentMethod);
        end
    end
end

2. 生成带Description列的测试结果表格

运行测试后,将结果转换为包含描述列的表格:

% 创建测试套件
testSuite = matlab.unittest.TestSuite.fromClass(?myClass);
% 执行测试并获取结果
testResults = run(testSuite);
% 构造包含描述列的结果表格
resultTable = table(...
    {testResults.Name}', ...
    {testResults.Description}', ...
    testResults.Passed, ...
    testResults.Failed, ...
    testResults.Duration, ...
    'VariableNames', {'测试方法', '测试描述', '通过', '失败', '耗时(秒)'});
% 打印表格
disp(resultTable);

执行后会输出包含测试注释的表格,示例格式如下:

测试方法测试描述通过失败耗时(秒)
myClass/addAandB测试两个整数的加法运算,验证结果是否符合预期truefalse0.012
myClass/multiplyXandY测试两个浮点数的乘法运算,处理边界值truefalse0.009

3. 生成包含测试描述的HTML报告

利用MATLAB的测试报告生成器,自动将描述同步到HTML报告中:

% 创建报告对象
testReport = matlab.unittest.reportgenerator.Report(testResults);
% 设置报告标题
testReport.Title = 'myClass单元测试报告';
% 生成HTML报告到指定路径
generateReport(testReport, 'OutputPath', 'myClass_Test_Report.html');

打开生成的HTML报告,每个测试用例的详情区域会显示对应的注释描述。

内容的提问来源于stack exchange,提问作者ndarkness

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 23:52:40