matt
matt

Reputation: 2039

Laravel: Unable to use include(app_path()) in PHPunit tests

I am trying to run unit tests on custom functions that I have in a file '\app\Custom\custom.php`

I am trying to include the custom file in my test file with:

include(app_path().'/Custom/custom.php');

but I get the error:

PHP Fatal error:  Uncaught Error: Call to undefined method Illuminate\Container\Container::path()

As per @habeebdev's answer, I have tried:

file path added to composer.json

...
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        },
        "files": ["app/Custom/custom.php"]
    },
...

laravel/tests/Unit/PracticeTest.php

<?php

namespace Tests\Unit;

use Tests\TestCase;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class PracticeTest extends TestCase
{
    /**
     * A basic unit test example.
     *
     * @return void
     */
    public function test_trueExample()
    {

        $user = User::find(1);

        $this->actingAs($user)
             ->assertEquals(true, can_transact());

    }
}

error:

 Call to undefined function Tests\Unit\can_transact()

EDIT:

I had a namespace App\Http\Controllers in my custom.php file. Once I prefixed my functions App\Http\Controllers\can_transact() it worked fine (Thanks @apokryfos)

Upvotes: 0

Views: 472

Answers (1)

habeebdev
habeebdev

Reputation: 278

You have to autoload the custom file. For this, please include custom.php in the 'autoload-dev' section of composer.json

"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
     },
     "files": ["app/Custom/custom.php"]
},

Run composer dump-autoload

Now you can call the custom function in your test script. No need to include the file.


Regarding the namespace, please change your custom.php namespace to App\Custom. Using Controller namespace for custom file is not good. Also, I recommend you to go through OOP and laravel basics.

Upvotes: 2

Related Questions