Search code examples
unit-testingsymfonyphpunithttp-error

Assert 403 Access Denied http status with PHPUnit test case


I have a custom error templates in my projects for 404, 403 and other exceptions. I want to create unit test case to assert http errors. When I am logging with user and accessing authorized page of Vendor I am getting 403 Access denied in browser but in Unit test case I am always getting 404 page not found error.

Here is my test scenario:

class ErrorExceptionTest extends WebTestCase
{
    public function testAccessDeniedException()
    {
        $server['HTTP_HOST'] = 'http://www.test.com/';
        $client = static::createClient(array('debug' => false), $server);
        $client->disableReboot();

        $session = $client->getContainer()->get('session');
        $firewall = 'main';

        $token = new UsernamePasswordToken('user', null, $firewall, array('ROLE_USER'));

        $session->set("_security_$firewall", serialize($token));
        $session->save();

        $cookie = new Cookie($session->getName(), $session->getId());
        $client->getCookieJar()->set($cookie);

        $client->request('GET', '/vendor/profile/edit');

        $this->assertEquals(403, $client->getResponse()->getStatusCode());
        $this->assertContains('Sorry! Access Denied',  $client->getResponse()->getContent());
    }
}

My test case is being failed, when I print response content it will show 404 error template.


Solution

  • Worked around it and find the issue. So, my solution is no need to use http host.

    public function testAccessDeniedException()
    {
        $client = static::createClient(array('debug' => false));
    
        $session = $client->getContainer()->get('session');
        $firewall = 'main';
    
        $token = new UsernamePasswordToken('user', null, $firewall, array('ROLE_USER'));
    
        $session->set("_security_$firewall", serialize($token));
        $session->save();
    
        $cookie = new Cookie($session->getName(), $session->getId());
        $client->getCookieJar()->set($cookie);
    
        $client->request('GET', 'fr/vendor/profile/edit');
    
        $this->assertEquals(403, $client->getResponse()->getStatusCode());
        $this->assertContains('Sorry! Access Denied',  $client->getResponse()->getContent());
    }