Question

I am trying to unit test a function which returns instantly and then returns the actual result by a callback function. Can anybody help me in how to unit test this function using cppunit.

for eg .

MyFunction(callback call) { .....

}

MyFunction returns success instantly and then the actual result in a callback function, from the callback an exception myexception is thrown how can I unit test to make sure that myexception is thrown?

Was it helpful?

Solution

The only way for MyFunction to return instantly is to have a working thread that eventually calls the callback function. If so then it is not possible to catch in your code an exception thrown from that working thread. You must catch all exceptions from within the working thread and handle them there. In the exception handler you may still call the callback function with parameters denoting that exception has occurred, and so inform the user about it.

OTHER TIPS

I would use xUnit++, and do this in two stages: test MyFunction, and test the callback.

FACT("MyFunction returns immediately")
{
    struct callback
    {
        callback()
            : success(false)
        {
        }

        void operator()() const
        {
            if (!success)
            {
                Assert.Fail() << "MyFunction executed callback before returning.";
            }
        }

        bool success;
    } cb;

    MyFunction(cb);

    cb.success = true;
}

FACT("The real callback throws an exception when complete")
{
   auto e = Assert.Throws<MyException>(myCallback);

   // further asserts for the value of e
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top