Set Expected Exception in Code

I want to do something like:

$I->setExpectedException('Laracasts\Validation\FormValidationException');

In functional cept. Any chance to do this?

\PHPUnit_Framework_TestCase::setExpectedException('Laracasts\Validation\FormValidationException');

The above code will work in isolation, but if I run codecept run, the tests get stuck after the test completes with the expected exception.

Here is my setup:

YML:

class_name: FunctionalTester
modules:
    enabled: [Filesystem, Db, FunctionalHelper, Laravel4, Asserts]
+4
source share
2 answers

I think this is a known issue with the Laravel 4 module for generating code, not sure if it will be fixed soon, but in the meantime I created a helper function to check for Exceptions:

In the tests / _support / FunctionalHelper.php file, add the following method:

public function seeExceptionThrown($exception, $function)
{
    try
    {
        $function();
        return false;
    } catch (Exception $e) {
        if( get_class($e) == $exception ){
            return true;
        }
        return false;
    }
}

Cepts :

$I = new FunctionalTester($scenario);
$I->assertTrue(
    $I->seeExceptionThrown('Laracasts\Validation\FormValidationException', function() use ($I){
    //All actions that you expect to generate the Exception
    $I->amOnPage('/users/edit/1');
    $I->fillField('name', '');
    $I->click('Update');
}));
+11

Mind:

public function seeException($callback, $exception = 'Exception', $message = '')
  {
    $function = function () use ($callback, $exception) {
      try {
        $callback();
        return false;
      }
      catch (Exception $e) {
        if (get_class($e) == $exception or get_parent_class($e) == $exception) {
          return true;
        }
        return false;
      }
    };
    $this->assertTrue($function(), $message);
  }

cepts

$I->seeException('Laracasts\Validation\FormValidationException', function() use ($I){
    //All actions that you expect to generate the Exception
    $I->amOnPage('/users/edit/1');
    $I->fillField('name', '');
    $I->click('Update');
})

, assertTrue . , , . , . , , .

, . FunctionalHelper.php _beforeSuite :

public function _beforeSuite()
  {
    parent::_beforeSuite();
    $this->assert = $this->getModule('Asserts');

  }

EDIT2 , , , , php , . ,

public function assertThrows($callback, $exception = 'Exception', $message = '')
  {
    $function = function () use ($callback, $exception) {
      $getAncestors = function($e) {

        for ($classes[] = $e; $e = get_parent_class ($e); $classes[] = $e);
        return $classes;

      }

      try {
        $callback();
        return false;
      }
      catch (Exception $e) {
        if (get_class($e) == $exception or in_array($e, $getAncestors($e))) {
          return true;
        }
        return false;
      }
    };
    $this->assertTrue($function(), $message);
  }
+1

All Articles