googletest

Is there a benefit of using EXPECT_NO_THROW in Google test?


In gtest one can use the EXPECT_NO_THROW macro to verify that an action does not throw an exception.

When the code does throw an exception, the test case will be marked as failed. However, if the EXPECT_NO_THROW macro is not used and an exception is thrown, the test case will fail too.

As far as I can observe the following are functionally equivalent:

sut.do_action();
EXPECT_NO_THROW(sut.do_action());

So, is there any benefit or reason to use EXPECT_NO_THROW? Or is its only purpose to make the test case specification more explicit?


Solution

  • Consider the following two benefits of using EXPECT_NO_THROW over not using a macro at all:

    1. It gives you ability to output something if an exception is thrown
      EXPECT_NO_THROW(sut.do_action()) << "Must not throw";
      
    2. It allows a test case to continue after an exception is thrown
      sut.do_action();
      std::cout << "Continue\n";  // does not output
      
      EXPECT_NO_THROW(sut.do_action());
      std::cout << "Continue\n";  // outputs regardless of an exception