Fabio
Fabio

Reputation: 31

Symfony 5 and API-Platform 2.5 functional test for Not allowed method


I have Symfony 5 and API-Platform 2.5, just installed with flex. I created User entity as API Resource, the collection list must be forbidden, so I created a functional test to check it.

The test pass correctly but I get also an error:

$ ./vendor/bin/simple-phpunit --filter=UsersTest::testGetCollection
PHPUnit 7.5.20 by Sebastian Bergmann and contributors.

Testing Project Test Suite
2020-05-03T21:50:50+00:00 [error] Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: "No route found for "GET /api/users": Method Not Allowed (Allow: POST)" at /srv/api/vendor/symfony/http-kernel/EventListener/RouterListener.php line 140
.                                                                   1 / 1 (100%)

Time: 691 ms, Memory: 30.00 MB

OK (1 test, 1 assertion)

I Would like to hide the error message.

Here are the files:

User Class

/**
 * @ApiResource(collectionOperations={"post"}, itemOperations={"get"})
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User
{
   /* some code */
}

Test

class UsersTest extends ApiTestCase
{
    use RefreshDatabaseTrait;

    /* some code */

    public function testGetCollection(): void
    {
        try {
            self::createClient()->request(Request::METHOD_GET, '/api/users');
            self::assertResponseStatusCodeSame(Response::HTTP_METHOD_NOT_ALLOWED);
        } catch (\Exception $e) {
        }
    }

    /* some code */
}

phpunit.xml.dist

<php>
    <ini name="error_reporting" value="-1" />
    <server name="APP_ENV" value="test" force="true" />
    <server name="SHELL_VERBOSITY" value="-1" />
    <server name="SYMFONY_PHPUNIT_REMOVE" value="" />
    <server name="SYMFONY_PHPUNIT_VERSION" value="7.5" />
</php>

Thanks!

Upvotes: 0

Views: 1632

Answers (2)

Mohammad.Kaab
Mohammad.Kaab

Reputation: 1105

I have checked the code, look like you haven’t used the monolog library in your code. And you were right the RouterListener will print out the error messages in case you haven’t defined any loggerIterface(log driver) for your project. as soon as you install the symfony/monolog-bundle you will not see those ugly messages again.

Upvotes: 3

Mohammad.Kaab
Mohammad.Kaab

Reputation: 1105

You can use

$client = self::createClient();
$client->catchExceptions(false);

But I'll suggest using

$client = self::createClient(); 
$client->request(Request::METHOD_GET, "/api/users");
$this->assertEquals(Response::HTTP_METHOD_NOT_ALLOWED, $client->getResponse()->getStatusCode());

instead of wrap the code with a try/catch

Upvotes: 0

Related Questions