0

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?

4

2 回答 2

3

MyFunction 立即返回的唯一方法是拥有一个最终调用回调函数的工作线程。如果是这样,那么就不可能在您的代码中捕获从该工作线程抛出的异常。您必须从工作线程中捕获所有异常并在那里处理它们。在异常处理程序中,您仍然可以使用表示发生异常的参数调用回调函数,并通知用户。

于 2012-11-02T09:59:24.780 回答
0

我会使用xUnit++,并分两个阶段执行此操作:测试MyFunction和测试回调。

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
}
于 2012-11-02T12:51:13.880 回答