CookieMonster's avatar

test case- how to get authentication exception?

I written a test case that a guest cannot create a thread if it's not authenticated.

In my threads controller"

  //Add middleware for authenticated user only
    public function __construct()
    {
        $this->middleware('auth')->only('store');
    }

My test case:


     /**
     * A basic feature test example.
     *
     * @test
     */
    function a_guest_may_not_create_a_thread(){

        $thread = factory('App\Thread')->make();
        
        $this->post('/threads', $thread->toArray());   
    
    }

When I run the php artisan test, it passes this but i should be expecting an authentication exception. Why it is not throwing it?

0 likes
5 replies
martinbean's avatar

@nickywan123 It’s not passing. It’ll just be running without making any assertions.

Like I said in another thread of yours, the point of tests is to test things. You’re just making a POST request to a URI. You’re not testing anything about that request, whether it was successful or not.

So, add an assertion. If you’re expecting to be redirected to the login page (because the user’s not authenticated, then add that assertion:

$this
    ->post('/threads', $thread->toArray())
    ->assertRedirect('/login');

Your test will now either pass (if the user is redirected to the login page) or fail if they aren’t for some reason.

CookieMonster's avatar

@martinbean It passes but what I am trying to achieve is how do I make it fail as because I want to verify that an unauthenticated user is not able to create the thread?

martinbean's avatar

@nickywan123 I literally told you how in my previous post.

And like I say, your test will be “passing” because it’s not performing any assertions.

CookieMonster's avatar

@martinbean i meant i added this is what i am expecting it to behave:

  function a_guest_may_not_create_a_thread(){
        $this->withoutExceptionHandling();
        $thread = factory('App\Thread')->make();

        $this->post('/threads', $thread->toArray())->assertRedirect('/login');
    
    }

That's what I am looking for.

Please or to participate in this conversation.