Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleTest: How to assert that a PHP error is thrown?

If I am correct, SimpleTest will allow you to assert a PHP error is thrown. However, I can't figure out how to use it, based on the documentation. I want to assert that the object I pass into my constructor is an instance of MyOtherObject

class Object {
    public function __construct(MyOtherObject $object) {
        //do something with $object
    }
}

//...and in my test I have...
public function testConstruct_ExpectsAnInstanceOfMyOtherObject() {
    $notAnObject = 'foobar';
    $object = new Object($notAnObject);
    $this->expectError($object);
}

Where am I going wrong?

like image 429
Andrew Avatar asked Mar 04 '09 20:03

Andrew


2 Answers

Type hinting throws E_RECOVERABLE_ERROR which can be caught by SimpleTest since PHP version 5.2. The following will catch any error containing the text "must be an instance of". The constructor of PatternExpectation takes a perl regex.

public function testConstruct_ExpectsAnInstanceOfMyOtherObject() {
    $notAnObject = 'foobar';
    $this->expectError(new PatternExpectation("/must be an instance of/i"));
    $object = new Object($notAnObject);
}
like image 167
Lawrence Barsanti Avatar answered Sep 21 '22 00:09

Lawrence Barsanti


PHP has both errors and exceptions, which work slightly different. Passing a wrong type to a typehinted function will raise an exception. You have to catch that in your test case. Eg.:

public function testConstruct_ExpectsAnInstanceOfMyOtherObject() {
  $notAnObject = 'foobar';
  try {
    $object = new Object($notAnObject);
    $this->fail("Expected exception");
  } catch (Exception $ex) {
    $this->pass();
  }
}

or simply:

public function testConstruct_ExpectsAnInstanceOfMyOtherObject() {
  $this->expectException();
  $notAnObject = 'foobar';
  $object = new Object($notAnObject);
}

But note that this will halt the test after the line where the exception occurs.

like image 24
troelskn Avatar answered Sep 19 '22 00:09

troelskn