Channels ▼

Adding Exception Testing to Unit Tests

April 2001/Adding Exception Testing to Unit Tests/Listing 1

Listing 1: A class for counting tests passed, tests failed, number of exception points, and which exception point to fail on

#ifndef COUNTER_H
#define COUNTER_H

#include <exception>
#include <iostream>
#include <typeinfo>
#include <strstream>

class TestException : public std::exception
    virtual const char* what() const throw() {
        return "TestException";

class Counter {
    // This variable indicates the number of the exception point
    // that we are up to executing in the code.
    static int sExceptionPointCount;
    // The number of the exception point which should throw.
    static int sThrowCount;
    static bool sDontThrow;

    // This counts the number of times new has successfully returned
    // a non-null result, minus the number of times a non-null ptr
    // has been passed to delete.
    static int sNewCount;

    static int sPassCount;
    static int sFailCount;

    static std::ostream* mOs;

    // This function should be called wherever an
    // exception could be generated in the real code.
    static void CouldThrow() throw ( TestException );

    // Functions for the test harness to use.
    static void SetThrowCount( int inCount ) throw();
     // Prevents throwing until next call to SetThrowCount()
    static void DontThrow() throw();
    static bool HasThrown() throw();

    // Return the number of currently allocated blocks.
    static int GetAllocationCount() throw();

    // Managing tests.
    static void Pass( const char* testName ) throw();
    static void Fail( const char* testName ) throw();
    static void Test( bool result, const char* testName ) throw();
    static void PrintTestSummary();

    // Managing where the output is sent. The default is cout.
    static void SetOutputStream( std::ostream* os );
    static std::ostream& GetOut(){ return *mOs; }

    // For use by our definitions of new and delete.
    static void* MemAllocated( void* rawMem );
    static void DoDeallocate( void* userMem );

    This method does the test. It will cause all 
    exception paths to be executed. 
    For example usage, see below.

template<class TestFunction>
void TestDriver()
    int i = 0;
    int start_count, leaks;
    bool thrown;
    Counter::GetOut() << "Doing test " 
                      << typeid( TestFunction ).name() 
                      << std::endl;

    do {
        start_count = Counter::GetAllocationCount();

        Counter::SetThrowCount( ++i );
        //Counter::GetOut() << std::endl 
        //    << "        Exception count: " << i << std::endl;
        try {
        catch( const TestException& e ) {
        catch( const std::bad_alloc& e ) {
        catch( ... ) {

        thrown = Counter::HasThrown();
        // Should set not to throw exceptions for the stuff below.
        // Check for resource leaks here. 
        // ...

    } while( thrown );
    // Loop terminates when we make it all the way
    // through a test without triggering the exception counter.
    Counter::GetOut() << "            " << i 
                      << " execution paths were tested." 
                      << std::endl;

To use this TestDriver function, supply a class like this:

class TestPath1
    static void DoTest() {
        // Test some aspect of your class or function here,
        // by calling it with known inputs and checking the results.
        // For example:
        // This tests the conversion constructor of a 
        // String class (assuming that operator== works OK).
        String s1(""), s2("Hello");
        Counter::Test( s1 == "", "Correct string value" );    
        Counter::Test( s2 == "Hello", "Correct string value" );    

Then, supply a main like this

int main()
    // and so on...
    return 0;


#endif // COUNTER_H
— End of Listing —

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.