If you want to write a cmath class, there is a method ABS (), the prototype is as follows:
Class cmath
{
Public:
Int ABS (int );
};
The general programming habit is to directly write code and then debug it. As for testing, let's talk about it later. TDD requires that you cannot write any product code before writing test code.
The test framework used here is cppunit. the use case code uses the format described in the first and second sections of this series. To reduce the length, only key codes are listed, for the usage of cppunit and the compilation of auxiliary code, see the first and second sections of this series.
First, compile the test code that will cause errors (including compilation errors) and define a test class:
Class testmath: Public cppunit: testcase
{
Public:
Void testabs ();
PRIVATE:
Cmath * pobj;
};
A compilation error occurs because the class cmath does not exist. Compile the cmath class definition so that the compilation passes:
Class cmath
{
};
Compile the test function of function ABS () and create only one use case:
Void testmath: testabs ()
{
// The first use case
Case_begin ("");
Int Arg = 1;
Int result = pobj-> ABS (ARG );
Cppunit_assert_equal (result, 1 );
Case_end ();
}
A compilation error occurs because cmath: ABS () does not exist. Write cmath: ABS (). Then, you can write an empty function. If there is a return value, you can write a return value to make the compilation pass:
Int cmath: ABS (INT Arg)
{
Return 0;
}
The test fails. Compile the function code to pass the test:
Int cmath: ABS (INT Arg)
{
If (Arg> = 0)
Return ARG;
Return 0;
}
After the test is passed, add a test case for the test function:
Void testmath: testabs ()
{
// The first use case
Case_begin ("");
Int Arg = 1;
Int result = pobj-> ABS (ARG );
Cppunit_assert_equal (result, 1 );
Case_end ();
// Use Case 2
Case_begin ("");
Int Arg =-1;
Int result = pobj-> ABS (ARG );
Cppunit_assert_equal (result, 1 );
Case_end ();
}
Test failed. Continue to write the code for cmath: ABS:
Int cmath: ABS (INT Arg)
{
If (Arg> = 0)
Return ARG;
Return ARG;
}
Test passed. Add another use case. The parameter is 0, and the test can pass without modifying the product code. When all functional points have been written and tested successfully, it indicates that the functions of the Code have been fully implemented. In this case, you should read and complete the Code, for example, improve the code structure, modify the inappropriate variable name, add necessary comments, improve the low-performance computing process, delete redundant code lines, and then perform the test again.