GoogleMock displays more detailed debugging information

I use googlemock at work. We often use EXPECT_THROW, EXPECT_NO_THROW, etc.

My question is, how do I get googlemock to display exception data and possibly a stack trace when the function wraps in EXPECT_NO_THROW but actually throws an exception (like a code error)?

The only result I get is that it threw an exception and failed the test ... which is not useful for debugging the root cause.

+6
source share
4 answers

EXPECT_THROW , EXPECT_NO_THROW , etc. really are part of Google Test , not Google Mock.

I do not know how to get additional information about the exception, except for hacking the gtest source. For std::exception only the next change should at least throw a what() exception when EXPECT_NO_THROW or ASSERT_NO_THROW .

In gtest / include / gtest / internal / gtest-internal.h, around line 1140, change the GTEST_TEST_NO_THROW_ macro to:

 #define GTEST_TEST_NO_THROW_(statement, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ try { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } \ catch (...) { \ try { \ std::exception_ptr exceptn_ptr(std::current_exception()); \ std::rethrow_exception(exceptn_ptr); \ } catch(const std::exception& exceptn) { \ std::cerr << exceptn.what() << '\n'; \ } \ goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ fail("Expected: " #statement " doesn't throw an exception.\n" \ " Actual: it throws.") 

Obviously, you can add more features; catching custom exception types, formatting error messages to include exception information, etc.

+2
source

You can also omit the alltogether statement, and let your test case throw an exception. Therefore, instead of saying that f() does not throw away:

 ASSERT_NO_THROW(f()); 

you just call the function:

 f(); 

If it throws an exception, it will give you the following result:

 C++ exception with description "something broke in f()" thrown in the test body. 

This, of course, only works with ASSERT_NO_THROW , because the test case will end.

+1
source

It was easiest for me to run gdb in unit test binaries. Fortunately, we compile all the code with debugging enabled =].

0
source

In general, GMock / GTest is not able to do anything with a caught object. You cannot simply assume that your code threw a subclass of std::exception as much as you would like, and C ++ does not provide any means to save trace stacks when exceptions occur, even if stack frames and debugging characters are actually present in your binary .

But then unit testing really is a test method, and other tools should be your friend for diagnostics. Whether this is the addition of temporary logging (like printf ) or an interactive debugger like gdb , there are better tools to work with.

0
source

Source: https://habr.com/ru/post/920258/


All Articles