More about Writing Tests

In our first example, we saw two of the assertions you can do: ASSERT and ASSERT_EQUALS. Use the former to test an arbitrary boolean condition; use the latter to check whether or not two objects are the same. If the two objects are not, in fact, the same, ASSERT_EQUALS will print out the actual and expected values. It assumes that the expected value is the first argument to ASSERT_EQUALS: thus you should write

    ASSERT_EQUALS(3, stack.top());

instead of

    ASSERT_EQUALS(stack.top(), 3);

To use ASSERT_EQUALS, the class that you are testing equality for must provide a comparison operator (operator!=, to be specific) and an output operator (operator<<). If you fail to provide one of these, your compiler will probably give you a quite verbose and not very helpful error message. If you don't have an output operator, you can just do

    ASSERT(a == b)

instead. (And if you find it hard to track down what went wrong in that situation, then take that as a sign that you should write an output operator!)

Those two are the workhorses of tests, but there's one other assertion: ASSERT_EXCEPTION. It's used when you want to check that an exception is thrown when you expect it. It takes two arguments: the expression that should give rise to the exception, and the type of the expression to be thrown. Here's an example:

    class EmptyPop {
    public:
      void run() {
        Stack stack;

        ASSERT_EXCEPTION(stack.pop(), Stack::PopException);
      }
    };

There's also a variant called ASSERT_EXCEPTION_MESSAGE. It takes a third argument, which is supposed to match the exception's what() string.


david carlton <carlton@bactrian.org>