Set Expected Exception in Codeception Functional Cept

Martin picture Martin · Jul 27, 2014 · Viewed 7.7k times · Source

I want to do something like:

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

In a functional cept. Any chance to do so?

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

Above code will work in isolation but if I run codecept run, the tests get stuck once the test with the expected exception is complete.

Here's my setup:

YML:

class_name: FunctionalTester
modules:
    enabled: [Filesystem, Db, FunctionalHelper, Laravel4, Asserts]

Answer

Mind picture Mind · Aug 10, 2014

I think this is a known problem with the Laravel 4 module for codeception, not sure if it is going to be fixed soon, but in the meantime I created a helper function to test Exceptions:

In the file tests/_support/FunctionalHelper.php 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;
    }
}

You use it in your Cepts like this:

$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');
}));