Symfony functional test fail but the same request works in browser

核能气质少年 提交于 2020-12-08 07:15:07

问题


I followed the Symfony documentation about functional tests in order to write my first one, but I have some issues. The response I get via browser works good:

But when I run phpunit -c app/ in the shell I get a failure.

1) AppBundle\Tests\Controller\MeterAPIControllerTest::testGetAllVariables Failed asserting that 500 matches expected 200.

This is the code:

<?php

namespace AppBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class MeterAPIControllerTest extends WebTestCase
{
    public function testGetAllVariables()
    {
        $client = static::createClient();
        $crawler = $client->request(
            'GET',
            '/meters/121/120/variables'
        );

        // Assert a specific 200 status code
        $this->assertEquals(200, $client->getResponse()->getStatusCode()); 
    }
}

If I try another test assertion, I get failure too.

// Assert that the "Content-Type" header is "application/json"
$this->assertTrue(
    $client->getResponse()->headers->contains(
        'Content-Type',
        'application/json'
    )
);

EDIT

When I run phpunit in app/logs/test.log I get a PHP Exception:

[2016-03-31 15:25:21] request.CRITICAL: Uncaught PHP Exception Doctrine\Common\Persistence\Mapping\MappingException: "Invalid mapping file 'AppBundle.Entity.EM2Meter.orm.yml' for class 'AppBundle\Entity\EM2Meter'." at /Applications/MAMP/htdocs/iso50k1_tst_symfony/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/MappingException.php line 86 {"exception":"[object] (Doctrine\Common\Persistence\Mapping\MappingException(code: 0): Invalid mapping file 'AppBundle.Entity.EM2Meter.orm.yml' for class 'AppBundle\Entity\EM2Meter'. at /Applications/MAMP/htdocs/iso50k1_tst_symfony/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/MappingException.php:86)"} []

How can I fix this?


回答1:


You have not told the symfony client to contact the localhost server on port 8000, its still defaulting to 80.

When you instantiate your client, specify the host like this.

$client = static::createClient([], [
    'HTTP_HOST' => 'localhost:8000',
] );



回答2:


It looks like there is a cache problem here. I think it is a good practice to clean cache for the current environment before running the tests and before running your project for functional tests:

$ php bin/console cache:clear --env=dev

$ php bin/console cache:clear --env=tests



来源:https://stackoverflow.com/questions/36326998/symfony-functional-test-fail-but-the-same-request-works-in-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!