views:

93

answers:

1

Hi, I have a few simple classes used in a forum application. I'm trying to run some tests using SimpleTest, but I'm having problems with exceptions.

I have a section of code which generates a custom exception. Is there a way to catch this exception in my test and assert that it is what I expect?

This is the method within my class:

public function save()
  {
      $this->errors = $this->validate();
        try
        {
            if (empty($this->errors))
            {
                Database::commitOrRollback($this->prepareInsert());
            } else {
                throw new EntityException($this->errors);
            } 
        } catch (Exception $e) {
        echo 'Caught exception: ',  $e->getMessage(), "\n";
        }      
  }

Any advice appreciated.
Thanks.

+1  A: 
function testSaveMethodThrows() {
  $foo = new Foo();
  try {
    $foo->save();
    $this->fail("Expected exception");
  } catch (EntityException $e) {
    $this->pass("Caught exception");
  }
}

Or use expectException:

troelskn