webRookie's avatar

Why I can not test that exception is throw?

Hi,

I can not test the exception is throw in my test case even if it is the test do not pas:

  1. Tests\Feature\QuizPageTest::test_if_questionID_is_invalid_redirect Failed asserting that exception of type "\Illuminate\Database\Eloquent\ModelNotFoundException" is thrown.

I have in testClass:

use Exception; use Illuminate\Database\Eloquent\ModelNotFoundException;

/** * @expectedException ModelNotFoundException * * @return */ public function test_if_questionID_is_invalid_redirect(){

        $this->call('addUserAnswer', 'POST');
}

I have in Controller

public function addUserAnswer(Request $request) {

   try{

       Quiz::findOrFail(300);


   }catch(Exception $e){

       dd($e);

   }

   return;
0 likes
6 replies
click's avatar

please use triple backticks around your code block

Your test is failing because you catch the exception in the controller yourself with the try { } catch () {} block.

Remove the try catch and it will throw an exception.

webRookie's avatar

I remove the try catch still not working


            $this->call('/addUserAnswer', 'POST', ['question_id'=>1000]);
            $this->expectException(ModelNotFoundException::class);
    }

  public function addUserAnswer(Request $request)
    {
           Quiz::findOrFail(300);

    }
click's avatar

You are searching for a quiz with id 300. Always.

So whatever you are sending with you request, it looks like 1000 in your test. It is never used. If you want to return a quiz based on the post variable you should retrieve that post variable within your controller.

public function addUserAnswer(Request $request)
{
    $quiz = Quiz::findOrFail($request->post('question_id'));
        // do whatever you need todo here. 
}
webRookie's avatar

Thank you. I put 300, because that id does not exist and is always throwing an error but I still can make that test to pass

click's avatar

You must add $this->expectException(ModelNotFoundException::class); above your $this->call() in your test

webRookie's avatar

Nop it's not working but I changed the test

  $response = $this->call('addUserAnswer', 'POST', ['quiz_id'=>999999999999])
              ->assertStatus(404);
            $response->assertSeeText('Invalid Quiz requested');

Please or to participate in this conversation.