Actually Andy, what I said was 'Write some code that does something and then assert that it has actually done it as you expected.' which means check to ensure that it has done what you expected. Yes there is an
assert()
function (well, macro) but this is only one way to assert that something is true or not. A simple if is an assertion mechanism.
1 2 3 4 5
|
if (X) {
doY();
} else {
doZ();
}
|
In that example,
doY()
is executed only when X is asserted to be true, otherwise
doZ()
is called.
Testing using the
assert()
macro is useful, even if it terminates the application as it states that something has gone horribly wrong that cannot be recovered from. I.e. it is outside of normal boundary conditions, so the programme has no sane way of handling or correcting for this. That's why the stopping of an attached the debugger, or the execution and attaching of a debugger, or the termination of the application is the result of a failed assertion using the assert() macro.
If something is outside of normal conditions but inside of exceptional conditions occurs, using exceptions is the way to go using the key words
try
/
catch
/
throw
. But that assumes that you can handle the exception, otherwise the programme will again terminate.
What a test suite can do is somewhat automate this process, but I've not found any general test suite that actually addresses all problems so using the "roll your own" is generally what is used. This comprises of a test function (usually a static function in the class you want to test) which runs some basic tasks that you expect your class to be able to handle and then verify that the class has handled each correctly. This can be done using an
assert()
if there is only one task to test or if the tasks depend on one another (there's no point in testing multiple tasks if they are dependent on the previous tasks done since if a task fails then any tests after that are invalid anyway). If the tasks are independent of each other, and you want to test all of them in one execution, then using the
assert()
macro is not the way to go.
Oh, one other thing. Though the
assert()
macro is in the <assert.h> header, there is nothing magical about it. You can roll your own
assert()
macro to make it do whatever you want it to. The <assert.h> file is mostly for convenience.