Expect_Throw - Actual: It Throws a Different Type, Google Tests
Hi Guys So I Have This Constructor Matrix: :Matrix(Size_T Row, Size_T Col) { If(Row < 1 || Col < 1) Throw New Std: :Runtime_Error("Minimalni Velikost Matice Je...
Hi guys so i have this constructor
Matrix::Matrix(size_t row, size_t col)
{
if(row < 1 || col < 1)
throw new std::runtime_error("Minimalni velikost matice je 1x1");
matrix = std::vector<std::vector< double > >(row,std::vector<double>(col, 0));
}
and this test
Matrix *TestedMatrix;
EXPECT_THROW(TestedMatrix = new Matrix(-2,3),std::runtime_error );
but im still getting that exepction is of different type. I also tried std::runtime_error* but result is the same. I wanted use EXPECT_ANY_THROW at first but it was not displayed in my code coverage. Thanks for help ! :)
2 Answers
Don't call new.
Matrix::Matrix(size_t row, size_t col)
{
if(row < 1 || col < 1)
throw std::runtime_error("Minimalni velikost matice je 1x1");
matrix = std::vector<std::vector< double > >(row,std::vector<double>(col, 0));
}
new is going to return a void* which is why you are getting the "exception is of different type" error.
Assuming that size_t is an alias for std::size_t, you're seeing signed-to-unsigned conversion here (and your compiler should be warning you about that; check that you've enabled sufficient warnings in your build).
-2 gets converted to a very large positive value (very nearly SIZE_MAX), so the likelihood is that the constructor is throwing std::bad_alloc.
You need to pass 0 to the constructor to exercise the code path that throws std::runtime_error*. (And you can simplify the check to if (!row || !col), since 0 is the only unsigned value less than 1).
EXPECT_THROW(Matrix(0,3), std::runtime_error*);
EXPECT_THROW(Matrix(3,0), std::runtime_error*);
As an aside, I recommend that you throw by value rather than using new.