google test assert throw
Certainly! Here's an example:
#include <gtest/gtest.h>
int Divide(int a, int b) {
if (b == 0) {
throw std::invalid_argument("Division by zero");
}
return a / b;
}
TEST(DivideTest, HandlesZeroDivisor) {
EXPECT_THROW(Divide(10, 0), std::invalid_argument);
}
TEST(DivideTest, HandlesNonZeroDivisor) {
EXPECT_EQ(Divide(10, 2), 5);
EXPECT_EQ(Divide(8, 4), 2);
}
Explanation:
1. #include <gtest/gtest.h>
- includes the Google Test framework header file.
Divide
function defines division operation between two integers. It checks if the divisor is zero and throws anstd::invalid_argument
exception if true.TEST(DivideTest, HandlesZeroDivisor)
- defines a test case namedDivideTest
with the specific test namedHandlesZeroDivisor
. This test checks whether theDivide
function throws an exception when dividing by zero usingEXPECT_THROW
.EXPECT_THROW(Divide(10, 0), std::invalid_argument);
- expects that theDivide
function called with arguments (10, 0) will throw anstd::invalid_argument
exception.TEST(DivideTest, HandlesNonZeroDivisor)
- defines another test case underDivideTest
namedHandlesNonZeroDivisor
. This test checks the expected results when dividing by a non-zero number.EXPECT_EQ(Divide(10, 2), 5);
- expects that the result of dividing 10 by 2 using theDivide
function is equal to 5.EXPECT_EQ(Divide(8, 4), 2);
- expects that the result of dividing 8 by 4 using theDivide
function is equal to 2.