www.gusucode.com > matlab 案例源码 matlab代码程序 > matlab/WriteSimpleTestCaseUsingClassesExample.m

    %% Write Simple Test Case Using Classes  
% This example shows how to write a unit test for a MATLAB(R) function,
% |quadraticSolver.m|.   

% Copyright 2015 The MathWorks, Inc.


%% Create quadraticSolver.m Function 
% The following MATLAB function solves quadratic equations. Create this
% function in a folder on your MATLAB path. 
%
% <include>quadraticSolver.m</include>
%
%% Create SolverTest Class Definition 
% To use the |matlab.unittest| framework,
% write MATLAB functions (tests) in the form of a _test case_, a class derived
% from |matlab.unittest.TestCase|. 
%
% Create a subclass, |SolverTest|. 
%
% <include>SolverTest_1.m</include>
%

%%
% The following steps show how to create specific tests. Put these tests
% inside the |methods| block with the |(Test)| attribute.  

%% Create Test Method for Real Solutions 
% Create a test method, |testRealSolution|, to verify that |quadraticSolver|
% returns the right value for real solutions. For example, the equation
% $x^{2} - 3x + 2 = 0$ has real solutions $x = 1$ and $x = 2$. This method
% calls |quadraticSolver| with the inputs of this equation. The solution,
% |expSolution|, is |[2,1]|. 
%
% Use the |matlab.unittest.TestCase| method,
% |verifyEqual| to compare the output of the function, |actSolution|, to
% the desired output, |expSolution|. If the qualification fails, the test
% continues execution. 
%
% <include>SolverTest_2.m</include>
%

%%
% Add this function inside the |methods (Test)| block.  

%% Create Test Method for Imaginary Solutions 
% Create a test to verify that |quadraticSolver| returns the right value
% for imaginary solutions. For example, the equation $x^{2} - 2x + 10 =
% 0$ has imaginary solutions $x = -1 + 3i$ and $x = -1 - 3i$. Add this function,
% |testImaginarySolution|, inside the |methods (Test)| block. 
%
% <include>SolverTest_3.m</include>
%

%%
% The order of the tests within the block does not matter.    

%% Save Class Definition 
% The following is the complete |SolverTest| class definition. Save this
% file in a folder on your MATLAB path. 
%
% <include>SolverTest.m</include>
%

%% Run Tests in SolverTest Test Case 
% Run all the tests in the |SolverTest| class definition file. 
testCase = SolverTest;
res = run(testCase)  

%% Run Single Test Method 
% To run the single test, |testRealSolution|: 
testCase = SolverTest;
res = run(testCase,'testRealSolution')