# 使用 MATLAB 单元测试插件生成工件

MATLAB® 单元测试框架使您能够使用 `matlab.unittest.plugins` 命名空间中的插件类自定义您的测试运行器。您可以使用其中一些插件类来生成测试报告和与持续集成 (CI) 平台兼容的工件：

### 使用自定义测试运行器运行测试

```function r = quadraticSolver(a,b,c) % quadraticSolver returns solutions to the % quadratic equation a*x^2 + b*x + c = 0. if ~isa(a,"numeric") || ~isa(b,"numeric") || ~isa(c,"numeric") error("quadraticSolver:InputMustBeNumeric", ... "Coefficients must be numeric.") end r(1) = (-b + sqrt(b^2 - 4*a*c)) / (2*a); r(2) = (-b - sqrt(b^2 - 4*a*c)) / (2*a); end ```

```classdef SolverTest < matlab.unittest.TestCase methods (Test) function realSolution(testCase) actSolution = quadraticSolver(1,-3,2); expSolution = [2 1]; testCase.verifyEqual(actSolution,expSolution) end function imaginarySolution(testCase) actSolution = quadraticSolver(1,2,10); expSolution = [-1+3i -1-3i]; testCase.verifyEqual(actSolution,expSolution) end function nonnumericInput(testCase) testCase.verifyError(@()quadraticSolver(1,"-3",2), ... "quadraticSolver:InputMustBeNumeric") end end end ```

```suite = testsuite("SolverTest"); ```

```import matlab.unittest.TestRunner runner = TestRunner.withTextOutput("OutputDetail",3); ```

```import matlab.unittest.plugins.TestReportPlugin pdfFile = "testreport.pdf"; p1 = TestReportPlugin.producingPDF(pdfFile); runner.addPlugin(p1) ```

```import matlab.unittest.plugins.XMLPlugin xmlFile = "junittestresults.xml"; p2 = XMLPlugin.producingJUnitFormat(xmlFile); runner.addPlugin(p2) ```

```import matlab.unittest.plugins.CodeCoveragePlugin import matlab.unittest.plugins.codecoverage.CoberturaFormat sourceCodeFile = "quadraticSolver.m"; reportFile = "cobertura.xml"; reportFormat = CoberturaFormat(reportFile); p3 = CodeCoveragePlugin.forFile(sourceCodeFile,"Producing",reportFormat); runner.addPlugin(p3) ```

```results = runner.run(suite) ```
``` Running SolverTest Setting up SolverTest Done setting up SolverTest in 0 seconds Running SolverTest/realSolution Done SolverTest/realSolution in 0.016834 seconds Running SolverTest/imaginarySolution Done SolverTest/imaginarySolution in 0.0043659 seconds Running SolverTest/nonnumericInput Done SolverTest/nonnumericInput in 0.0086213 seconds Tearing down SolverTest Done tearing down SolverTest in 0 seconds Done SolverTest in 0.029822 seconds __________ Generating test report. Please wait. Preparing content for the test report. Adding content to the test report. Writing test report to file. Test report has been saved to: C:\work\testreport.pdf results = 1×3 TestResult array with properties: Name Passed Failed Incomplete Duration Details Totals: 3 Passed, 0 Failed, 0 Incomplete. 0.029822 seconds testing time. ```

```dir ```
```. .. GenerateArtifactsUsingMATLABUnitTestPluginsExample.m SolverTest.m cobertura.xml html junittestresults.xml metadata quadraticSolver.m testreport.pdf ```

```open("testreport.pdf") ```