PHP SimpleTest - exception handling

I have some simple classes used in a forum application. I am trying to run some tests using SimpleTest, but I have problems with exceptions.

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

This is the method in 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.

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

Or use expectException:

+5
source

Source: https://habr.com/ru/post/1724122/


All Articles