Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

EXPECT_THROW - Actual: it throws a different type, google tests

Writer Olivia Zamora

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

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.

3

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.