Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

victoragung@gmail.com's avatar

PHPUnit throws error but works when specifying the specific test

I recently upgraded our codebase to use Laravel 5.6 and I'm finding a weird issue where phpunit will fail with the following error message: PHP Fatal error: Cannot declare class Tests\Feature\CreateVisitorTest, because the name is already in use in /var/www/grow/tests/Feature/CreateVisitorTest.php on line 12

However if I were to specify the file specifically it works fine. e.g., this command works and my test passes: phpunit tests/feature/CreateVisitorTest.php

I've tried doing composer dump-autoload

Any other ideas?

0 likes
4 replies
Talinon's avatar

You probably have the same test class name defined in another test file somewhere. This happens to me occasionally if I copy the boilerplate of a test class to a new file and forget to change the class name.

victoragung@gmail.com's avatar

That's what I thought too, but I've searched everywhere and that's definitely the only test with that file name and class name.

siangboon's avatar

Agreed with Talinon, the error is so obvious and the system won't lie. You should double check that very carefully. I suspect that you may defining the test function name as the same test class name.

victoragung@gmail.com's avatar

Turns out the phpunit config (phpunit.xml) was reading the same file twice.

Config that caused the error:

    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>./tests/</directory>
        </testsuite>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>
        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>
    </testsuites>

Updated config to remove the overlap:

    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>
        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>
    </testsuites>
1 like

Please or to participate in this conversation.