Johann Gerell
Johann Gerell

Reputation: 25581

Howto combine unit testing with assert()

Suppose that the preconditions of my object's functions are checked with assert(). How can I then, without ripping my hair off in the process, write meaningful unit tests that catches the precondition failures when I pass invalid parameters to the functions?

I mean, assert() will abort(), so how can I then perform all other tests after that?

Upvotes: 5

Views: 635

Answers (3)

William Pursell
William Pursell

Reputation: 212168

Run your tests in a sub-process. Passing invalid parameters will cause the child to abort, but your test (the parent) continues running.

Upvotes: 3

user2100815
user2100815

Reputation:

As time passes, I've become less and less keen on using assert. But if you want to use it, I suggest writing your own version which throws exceptions (which can be caught), rather than calling abort().

Upvotes: 4

David Heffernan
David Heffernan

Reputation: 612794

You could replace assert() with a macro that calls your unit-testing framework when unit-testing but evaluates to assert() otherwise.

Upvotes: 5

Related Questions