Getting started with cppunit testing framework

Source: Internet
Author: User
Tags xunit

Getting started with cppunit testing framework

Author: cpluser

Download source code

Test-driven development (TDD) is the center of the development process. It insists thatCodeBefore that, write the test code based on the product code. The goal of the development process is to first pass the test and then optimize the design structure. Test-driven development is an important part of extreme programming. Xunit, a test framework based on test-driven development, provides a convenient tool for us to use test-driven development during the development process, so that we can quickly perform unit testing. There are many xunit members, such as JUnit and pythonunit. Cppunit is a member of the xunit family. It is a test framework specially designed for C ++.

This article does not give a detailed introduction to the cppunit source code, but just introduces the cppunit application. In this article, you will see:

        1. cppunit Source code.
        2. How to set up your development environment to use cppunit.
        3. How to add the test code for your product code (in fact, you should add the product code to the test code in turn. In TDD, there are first test code and then product code), and the test is carried out through cppunit.

    The background of this article is cppunit1.9.0, Visual C ++ 6.0, and Windows2000. If the description is incorrect, please criticize and correct it.

    I. cppunit Source Code Composition

    The source code for the cppunit testing framework can be downloaded from the http://sourceforge.net/projects/cppunit. After downloading and decompressing the package, you will see the following folder:


    Figure 1

    The main folders are:

      • DOC: cppunit instructions. In addition, there are three instruction documents in the Code root directory, which are respectively install,install-unix,install-win32.txt.
      • Examples: The example provided by cpppunit is also a test of cppunit itself, through which you can learn how to use the cppunit testing framework for development.
      • Include: cppunit header file.
      • SRC: cppunit source code directory.

    Ii. Initial Knowledge of cppunit test environment

    After extracting the source code package, you must take a look at what cppunit is like? OK. Let's unveil the secrets of cppunit:

    1. Enter the example folder and use VC to open examples. DSW. Let's take a look at the test examples provided by cppunit. These examples are all unit test sets for cppunit itself. On the one hand, this is the test cases written during the cppunit framework developed by cppunit authors, and on the other hand, we can use these examples to learn how to add test cases in our own projects.

    2. Set the cppunittestapp project to active project (Win32 Debug), compile and run it, and you can see the GUI of cppunit for unit test testrunner. Click "run". The page shown in Figure 2 is displayed:


    Figure 2

    This is a unit test result for cppunit. It indicates that we have passed 11 tests just now.
    Click "Browse". You can also choose the unit test you want to perform:


    Figure 3

    Cppunit indicates all unit tests in the tree structure. In cppunit, the smallest test unit is called the testmethod test method, and multiple related test methods can form a testcase test case. Multiple test cases form the testsuite test package. Test packages are nested together to form the tree structure we see above. We can choose any of the Tree nodes for unit testing.

    3. Set the cppunittestmain project to active project (Win32 Debug), compile and run it, and let's look at another unit test environment. 4:


    Figure 4

    This is a text-based unit test environment. Cppunit provides several test environments, one based on text and the other based on GUI, that is, figure 3.

    4. Set the hostapp project to active project (Win32 Debug) and compile and run it. V:


    Figure 5

    This is also a test of cppunit itself, but it shows us various failed tests. In a GUI-based test environment, if the test fails, the progress bar is displayed in red, and vice versa. From the test results, we can see the name of the failed unit test, the reason for the test failure, and the file and number of lines of the statement where the test fails.

    3. cppunit Development Environment Settings

    After learning about the cppunit test environment, you must be ready to feel the feeling of test-driven development during your development process. However, you need to set up your development environment before using cppunit.

    1. lib and DLL of cppunit
    Cppunit provides two sets of framework libraries: static lib and dynamic DLL.

    Cppunit project: static lib
    Cppunit_dll project: Dynamic DLL and Lib

    In development, we can make a choice based on the actual situation. Go to the SRC folder and open cppunitlibraries. DSW. Compile the two projects respectively, and the output location is the Lib folder.
    Another project that requires attention is testrunner, which outputs a DLL and provides a GUI-based test environment, that is, one of the two test environments we mentioned earlier. We also need to compile this project, and the output location is also the Lib folder.
    To facilitate development, we copy the compiled lib and DLL (including the debug and release versions) to a folder created by ourselves (you can also skip this ), for example, F: \ cppunit1.9.0 \ Lib \. We also copy the include folder in the cppunit source code to our own include folder. Set the include path and Lib path in tools/options/directories/include files and library files of VC. Finally, do not forget to link the correct Lib in your project.

    2. Enable the rtti switch in your VC project.
    The specific location is Project Settings/C ++ language.

    3. Set environment variables for testrunner. dll
    Testrunner. dll provides a GUI-based testing environment. To make our testsProgramTo call it correctly, testrunner. dll must be located in the path of your test program. However, the simplest method is to add the testrunner. dll path in the environment variable path of the operating system, which is the most convenient.

    4. Your first TDD example

    Everything is ready. Now let's take a look at how to add the test code. As mentioned above, the smallest unit of cppunit is testcase, and multiple related testcase forms a testsuite. The simplest way to add test code is to use several macros that cppunit provides for us (of course there are other manual addition methods, but they all share the same path, you can refer to the Demo code in the cppunit header file ). These macros are:

     
    Cppunit_test_suite () start to create a testsuite cppunit_test () add testcase cppunit_test_suite_end () end to create testsuite catalog () Add a testsuite to a specified testfactoryregistry Factory

    If you are interested, you can go to helpermacros. h to check the macro statements. This article will not detail them here.

    1. a class that adds two integers
    Suppose we want to implement a class, and the class name is temporarily used as cplus. Its function is mainly to implement the addition of two numbers (a more simple class, should this be tested? It doesn't matter, we just know how to add the test code to test it, so the simpler the better ). Assume that the method to implement the addition of this class is:

     
    Int add (INT nnum1, int nnum2 );

    OK. Let's write the code for testing this method first. TDD writes the test code first, and then the product code (cplus! The test code written first often cannot be run or compiled. Our goal is to write the product code after writing the test code so that the code can be compiled and then restructured. This is what Kent Beck calls "red/green/refactor" (Do you still remember the status bar of the GUI-based test environment ?). Therefore, the above class name and method should be in your mind, but also your idea.

    2. Create a project for the test code in VC
    Generally, the test code and the tested object are in different projects. In this way, your product code will not be contaminated by the test code ".
    In this example, a GUI-based test environment is created. In VC, we create a project based on the dialog box. Don't forget to link the correct Lib. In this example, we use static cppunit Lib. Because we want this project to display an interface like Figure 2 after running, we need to block the original dialog box in the app instance () and replace it with the cppunit GUI.

     
    Cppunit: mfcui: testrunner runner; runner. addtest (plustest: Suite (); // Add a test runner. run (); // show UI/* ccplustestdlg DLG; m_pmainwnd = & DLG; int nresponse = DLG. domodal (); If (nresponse = idok) {// todo: Place code here to handle when the dialog is // dismissed with OK} else if (nresponse = idcancel) {// todo: Place code here to handle when the dialog is // dismissed with cancel }*/

    As mentioned above, the dialog box like Figure 2 is output by testrunner, which is why we set the environment variable for the path of testrunner. dll.
    Note: plustest: Suite () returns a pointer to cppunit: test. This pointer is the starting point of the test. Cppunit: testfactoryregistry: getregistry () returns the testfactoryregistry factory based on the testsuite name, and then calls maketest () in the factory to assemble the testsuite. This is a recursive call, A tree-like test structure will be created.

     
    Namespace plustest {cppunit: test * Suite () {cppunit: testfactoryregistry istry = cppunit: testfactoryregistry: getregistry (plussuitename (); Return registry. maketest ();}}

    In addition, do not add the header file:

     
    # Include "cplustestsuite. H"
    # Include <cppunit/UI/mfc/testrunner. h>
    # Include <cppunit/extensions/testfactoryregistry. h>

    3. Add a class to the project named cplustestcase
    Cplustestcase inherits from cppunit: testcase. The Code is as follows:

    Class cplustestcase: Public cppunit: testcase {cppunit_test_suite (cplustestcase); cppunit_test (testadd); cppunit_test_suite_end (); Public: cplustestcase (); Virtual ~ Cplustestcase (); void testadd (); // test method };

    Have you seen these macros? They showed up here.

     
    Cppunit_test_suite (cplustestcase); cppunit_test (testadd); cppunit_test_suite_end ();

    With these macros, we have registered cplustestcase and testadd to the test list.
    In addition, we need to add another macro to the CPP file:

     
    Cppunit_test_suite_named_registration (cplustestcase, plustest: plussuitename ());

    It registers the testsuite cplustestcase to a specified testfactory. This testsuite is identified by the name returned by the plustest: plussuitename () function () in the function, the name is used to obtain the factory ). Plussuitename () is a function in the namespace of plustest. It returns the name we created for this testsuite (in this example, we named "plus "). In fact, we do not need to do this, simply write "plus" in the macro. However, this prevents hard encoding from causing problems.

    In the test class, we added a Test method:

     
    Void testadd ();

    The test object is the method of the cplus class mentioned above:

     
    Int add (INT nnum1, int nnum2 );

    Let's take a look at its implementation:

     
    Void cplustestcase: testadd () {cplus plus; int nresult = plus. add (10, 20); // execute the add operation cppunit_assert_equal (30, nresult); // check whether the result is equal to 30}

    Cppunit_assert_equal is a macro that determines the result. For other macros similar to cppunit, see testassert. H. This article will not detail them here.
    In addition, we can override the setup () and teardown () Functions of the base class. These two functions are actually a template method. Before the test is run, setup () is called for initialization. After the test is completed, teardown () is called () to do some "aftercare", such as resource recycling. Of course, you can also not override these two functions, because they are defined as empty methods in the base class, rather than pure virtual functions. In addition, add the header file to CPP:

    # Include "plussuite. H"

    4. Compile the product code based on the test code
    Compile the test code above. The compiler will tell us that the cplus class is not declared, because we have not implemented the cplus class yet! The current job is to implement the cplus class immediately and let the compilation pass. Now you should smell a little bit of "test drive?
    Create a project of MFC extension DLL in VC and add the class cplus to this project. Its declaration is as follows:

     
    Class afx_ext_class cplus {public: cplus (); Virtual ~ Cplus (); Public: int add (INT nnum1, int nnum2 );};

    There is only one method, that is, the method for testing the test code. Let's take a look at its implementation:

     
    Int cplus: add (INT nnum1, int nnum2) {return nnum1 + nnum2 ;}

    It's very simple, isn't it? Now let the previous project dependent that contains the test code, the include header file, rebuild all, and you will find that the compilation has passed. Have you realized that the test code is driving the product code? Of course, our example is still very simple, and we have not reconstructed this step.
    Run our test program and you will see the six interfaces:


    Figure 6

     

     

     

     

    Click Browse:


    Figure 7

    Now you should have a better understanding of the testsuite name we mentioned earlier. Plus is a test suite, which contains a test case, which contains a test method.
    So far, we have made a detailed introduction to the application of the cppunit testing framework, hoping to help you in the TDD process.

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.