使用函数编写简单测试用例

您所在的位置:网站首页 matlab编写程序在哪里编写 使用函数编写简单测试用例

使用函数编写简单测试用例

2024-04-13 21:56| 来源: 网络整理| 查看: 265

创建测试

要测试 quadraticSolver 函数,请在当前文件夹中创建测试文件 quadraticSolverTest.m。然后,在文件中定义主函数和两个局部函数,针对实数解和虚数解测试 quadraticSolver。主函数和局部函数的名称必须以单词“test”开头或结尾,且不区分大小写。此外,主函数的名称必须对应于测试文件的名称。

定义主函数

要运行基于函数的单元测试,您必须定义主函数,它将所有局部测试函数收集到一个测试数组中。在测试文件中定义主函数 quadraticSolverTest。主函数调用 functiontests 来生成测试数组 tests。将 localfunctions 传递给 functiontests,以自动生成由文件中局部函数的函数句柄组成的元胞数组。

function tests = quadraticSolverTest tests = functiontests(localfunctions); end 创建局部测试函数

将局部函数添加到测试文件中,以针对实数解和虚数解测试 quadraticSolver 函数。各测试在该文件中的顺序无关紧要。每个局部函数必须接受单个输入 testCase,它是一个 matlab.unittest.FunctionTestCase 对象。测试框架自动生成此对象。函数使用该对象来执行对测试值和对失败进行响应的鉴定。

定义局部函数 testRealSolution,以验证 quadraticSolver 返回特定系数的正确实数解。例如,方程 x2-3x+2=0 有实数解 x=1 和 x=2。函数使用此方程的系数调用 quadraticSolver。然后,它使用 verifyEqual 鉴定函数将实际输出 actSolution 与预期输出 expSolution 进行比较。

function tests = quadraticSolverTest tests = functiontests(localfunctions); end function testRealSolution(testCase) actSolution = quadraticSolver(1,-3,2); expSolution = [2 1]; verifyEqual(testCase,actSolution,expSolution) end

定义另一个局部函数 testImaginarySolution,以验证 quadraticSolver 返回特定系数的正确虚数解。例如,方程 x2+2x+10=0 有虚数解 x=-1+3i 和 x=-1-3i。就像前面的函数一样,此函数用此方程的系数调用 quadraticSolver,然后使用 verifyEqual 鉴定函数将实际输出 actSolution 与预期输出 expSolution 进行比较。

function tests = quadraticSolverTest tests = functiontests(localfunctions); end function testRealSolution(testCase) actSolution = quadraticSolver(1,-3,2); expSolution = [2 1]; verifyEqual(testCase,actSolution,expSolution) end function testImaginarySolution(testCase) actSolution = quadraticSolver(1,2,10); expSolution = [-1+3i -1-3i]; verifyEqual(testCase,actSolution,expSolution) end 运行测试文件中的测试

使用 runtests 函数运行在 quadraticSolverTest.m 文件中定义的测试。在此示例中,两个测试都通过。

results = runtests('quadraticSolverTest.m')Running quadraticSolverTest .. Done quadraticSolverTest __________ results = 1×2 TestResult array with properties: Name Passed Failed Incomplete Duration Details Totals: 2 Passed, 0 Failed, 0 Incomplete. 0.016572 seconds testing time.

您也可以使用 run 函数运行测试。

results = run(quadraticSolverTest)Running quadraticSolverTest .. Done quadraticSolverTest __________ results = 1×2 TestResult array with properties: Name Passed Failed Incomplete Duration Details Totals: 2 Passed, 0 Failed, 0 Incomplete. 0.0072908 seconds testing time.


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3