Catch Exceptions in functional tests

Hi there,

I need some help with functional tests.

I want to test logout action:

I try to make GET request to logout method and I want to catch exception ‘Method Not Allowed. This url can only handle the following request methods: POST.’

How can I catch this exception in a test?

I tried





... here is success login action ...


$I->amGoingTo('try to logout by url');

try {

  $I->amOnPage(Yii::$app->urlManager->createUrl('site/logout'));

} catch(Exception $exc) {

  $I->expectTo('see error page');

  $I->see('Method Not Allowed. This url can only handle the following request methods: POST.');

}



also I tried




$I->amGoingTo('try to logout by url');

try {

  $I->amOnPage(Yii::$app->urlManager->createUrl('site/logout'));

} catch(Exception $exc) {

  

}

$I->expectTo('see error page');

$I->see('Method Not Allowed. This url can only handle the following request methods: POST.');



But test did not pass because


$I->amOnPage(Yii::$app->urlManager->createUrl('site/logout'));

don’t navigate $I to another page and $I get previous page when trying to


$I->see('Method Not Allowed. This url can only handle the following request methods: POST.');

What am I doing wrong?

Thank you!

Found some kind of the solution.

Create helper [b]tests/_support/FunctionalHelper.php

[/b]




public function seeExceptionThrown($exception, $function)

{	

	try {

        	$function();

        	return false;	

    } catch (Exception $e)  {

        	if( get_class($e) == $exception ) {

            	return true; 		

        	}

        	return false;

	}

}



[b]

[/b]And then use next code to catch exceptions




$I = new FunctionalTester($scenario);

$I->assertTrue( 	

	$I->seeExceptionThrown('yii\web\MethodNotAllowedHttpException', function() use ($I) {

        	//All actions that you expect to generate the Exception      	

        	$I->amOnPage(Yii::$app->urlManager->createUrl('site/logout'));

    })

);



The test is passed, but marked as risky.