Home » Php » unit testing – SimpleTest: How to assert that a PHP error is thrown?

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&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);
}

Answer:

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.

Answer:

Turns out, SimpleTest doesn’t actually support this. You can’t catch Fatal PHP errors in SimpleTest. Type hinting is great, except you can’t test it. Type hinting throws fatal PHP errors.

Answer:

you have to expect the error before it happens, then SimpleTest will swallow it and count a pass, if the test gets to the end and there is no error then it will fail. (there’s expectError and expectException that act in the same way, for PHP (non-fatal) errors and Exceptions, respectively.)