baskarks's avatar

laravel 11, automatically considerTestCase in all test file

instead of adding TestCase\TestCase, how to consider it automatically

0 likes
6 replies
LaryAI's avatar
Level 58

To automatically consider a base TestCase class in all your test files in Laravel, you can leverage PHPUnit's configuration file (phpunit.xml). By setting a default bootstrap file in your phpunit.xml, you can ensure that your custom TestCase class is always included.

Here’s how you can do it:

  1. Create a TestCase class: Ensure you have a base TestCase class in your tests directory. This is typically located at tests/TestCase.php.

    <?php
    
    namespace Tests;
    
    use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
    
    abstract class TestCase extends BaseTestCase
    {
        use CreatesApplication;
    }
    
  2. Modify phpunit.xml: Open your phpunit.xml file located at the root of your Laravel project. Add or modify the bootstrap attribute to point to your TestCase.php file.

    <phpunit bootstrap="tests/TestCase.php">
        <!-- other configurations -->
    </phpunit>
    

By setting the bootstrap attribute, PHPUnit will automatically include your TestCase class before running any tests. This way, you don't need to manually include TestCase in each test file.

Here’s an example of what your phpunit.xml might look like:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="tests/TestCase.php"
         colors="true"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>
        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>
    </testsuites>
    <coverage processUncoveredFiles="true">
        <include>
            <directory suffix=".php">./app</directory>
        </include>
    </coverage>
</phpunit>

With this setup, PHPUnit will automatically consider your TestCase class for all test files, and you won't need to manually include it in each test file.

baskarks's avatar

@martinbean I am trying to migrate lumen to laravel. I cant able to run test case which already written in lumen. I am getting Message: Class "TestCase" not found. So instead of adding Illuminate\Foundation\Testing\TestCase in all file. I am looking one place to fix it

baskarks's avatar

@martinbean Do we need to include this class in all test cases or is there any way to add this one place which will consider in all test cases

Please or to participate in this conversation.