Reputation: 15337
I'm writing a new class where I have inserted a C++ assert()
to verify correctness of state.
I would like to use googletest to verify that this assert is being called in the way I expect, but I can't seem to find a way to do this.
Should I be throwing exceptions instead or is there some other googletest-testable way to validate the state of an object?
Edit: I am also open to gmock alternatives (looking into that now).
Upvotes: 1
Views: 2230
Reputation: 7756
Assertions behave differently on different platforms. If they print a message and terminate the program on yours, you can use Google Test's death tests to verify them. Put a statement that is expected to terminate the program into the EXPECT_DEATH
macro:
EXPECT_DEATH(MyFunction(with_argument_that_causes_it_to_abort), "");
This will run the statement in a subprocess and verify that the statement terminates it. You can supply a regular expression in the second parameter to match the subprocess output. This macro was created specifically to verify assert-like calls.
A code built with Visual Studio may display a dialog box and wait for user reaction instead of printing a message, making death tests inconvenient. But you should be able to configure the assertion behavior to not do that.
Upvotes: 2
Reputation: 2986
If you are using googletest, shouldn't you be using ASSERT_TRUE() instead of assert()? That said, from my reading of http://code.google.com/p/googletest/wiki/Primer you should be able to use assert(), ASSERT_TRUE() or throw to cause a test to fail.
On exceptions vs assert's, you should use assert if you know the error condition can never be encountered when released to the user (assuming correct behaviour of other system components). If there is some way that the error condition can be caused by the user's input, you should throw an exception.
Upvotes: -1