Aerendir
Aerendir

Reputation: 6399

Symfony and PHPUnit: Exception thrown but not intercepted by setExpectedException

I wrote a test for a controller that saves in the database some data passed by a form.

I wrote the following test method to be sure that if the form is empty an exception is thrown:

public function testRegisterNewMerchantExceptionNoDataSubmitted()
{
    $client = static::createClient();
    $crawler = $client->request('GET', '/getstarted');

    $form = $crawler->selectButton('getStarted[submit]')->form();
    $form['getStarted[email]'] = '';

    $this->setExpectedException('DomainException');
    $client->submit($form);

    $this->assertEquals(500, $client->getResponse()->getStatusCode());

    //dump($client->getResponse());die;
}

The method i'm testing is the following:

public function endAction(Request $request)
{
    $form = $this->createForm(new GetStartedType());

    $form->handleRequest($request);

    if ($form->isValid()) {
        // Get data from form
        $data = $form->getData();
    } else {
        throw new  \DomainException('No data submitted.');
    }

    ...

I'm sure that also during tests the exception is thrown because dumping the Response object the page is a 500 error reporting the exact message "No data submitted". More, the assertEquals test on the status code is successful, so there are no doubts that the exception is correctly thrown.

But the $this->setExpectedException() test doesn't intercept it and returns a fail of the test.

Any idea about why this happens?

Upvotes: 1

Views: 1530

Answers (1)

Trowski
Trowski

Reputation: 469

Using $this->setExcpectedException() tells PHPUnit to expect the given exception type to be thrown from the test method, not just that an exception of that type is thrown at some point during execution.

When you throw an exception in a controller method, the Symfony controller catches that exception and creates a 500 response. This means the exception will not be thrown from the test method, so the test fails. Your test looks reasonable otherwise, so removing $this->setExpectedException() should solve the problem and test the behavior you intended.

Upvotes: 3

Related Questions