Unit tests and verifying pre/post-conditions and invariants

Jonathan M Davis jmdavisprog at gmail.com
Sat Aug 14 20:49:18 PDT 2010


Is there a standard and/or acceptable way to make sure that pre-conditions, 
post-conditions, or invariants _fail_ when running unit tests? That is, lets say 
I had a function like this

void func(int x)
in
{
    assert(x < 8);
}
body
{
  //...
}


and I wanted to test to make sure that func() couldn't be called with any int 
greater or equal to 8, what would I do? The best that I can think of is to catch 
an AssertError and ignore it. e.g.

unittest
{
    try
    {
        func(8);
        assert(0);
    }
    catch(AssertionError ae)
    {}
}


But catching AssertionErrors is generally a bad idea. As I understand it, when 
anything derived from Error is thrown, code is not left in a proper state, with 
stuff like destructors being skipped. Would it be okay to catch it in a case like 
this, or is it a really bad idea? If it's a bad idea, I haven't a clue how to 
verify that pre-condition, post-conditions, and invariants are correct.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list