Search code examples
c++c++11exceptionlambdagoogletest

GoogleTest Framework seems not to work with Lambda functions (follow up)


This is a follow up to my last question:

Google Test macros seem not to work with Lambda functions

The solution mentioned in that case worked for that particular case, namely, the constructor of a template class inside the lambda could be wrapped in parantheses and the build would succeed. And I accepted that answer. But the question still remains, that the GoogleTest Framework seems not to work with Lambda functions. I see nothing on this in the documentation.

I did the following test,

TEST(errorhandlingInterpolator, NOTtoolargeInput) {
    ASSERT_NO_THROW(throw);
}

which would cause the test to fail. Good.

Then, I did this,

TEST(errorhandlingInterpolator, NOTtoolargeInput) {
        ASSERT_NO_THROW([](){throw;});
}

which would cause the test NOT to fail. Strange.

So, finally to be thorough about (something so trivial), I tested the following bit.

void dummy() { throw; }

TEST(errorhandlingInterpolator, NOTtoolargeInput) {
        ASSERT_NO_THROW(throw);
}

and the exception caused the test to fail. All good.

Which raised a flag in my head, do exceptions even work with lambda functions. I thought they were just like normal functions, except anonymous. Apparently they do. The following two questions talk about this.

Can C++ lambda-expression throw?

throw an exception from a lambda expression, bad habit?

So, it really does seem to boil down to the fact that the macros in google test framework do NOT work with lambda functions.


Solution

  • The expression in ASSERT_NO_THROW([](){throw;}) does not execute an exception, it simply declares a lambda, which is then discarded, because it's not assigned to anything.

    You want ASSERT_NO_THROW([](){throw;}()), which immediately attempts to execute the lambda.