Slim Test Error: Function name must be a string

Slim Test Error: Function name must be a string

我正在设置一个 PHP Slim 3 样板项目,我正在尝试设置一个我可以 运行 我的测试的环境。

为此,我创建了一个设置 php class 文件,该文件继承了 PHPUnit (v 7.5) 测试 class,我的测试 classes 会继承。

这是我的测试文件的样子:

// Testcase.php
<?php

use Slim\App;
use PHPUnit\Framework\TestCase as BaseTestCase;

class TestCase extends BaseTestCase
{
    protected $app;

    protected $withMiddleware = true;

    protected function setUp()
    {
        parent::setUp();

        $this->createApplication();
    }

    protected function createApplication()
    {
        $config = require_once __DIR__ . '/../config/index.php';

        $app = new App(['settings' => $config]);

        $dependencies = require_once __DIR__ . '/../bootstrap/dependencies.php';
        $dependencies($app); // Line 26

        $routes = require_once __DIR__ . '/../routes/web.php';
        $routes($app);

        $this->app = $app;
    }

    public function request(string $request_method, string $request_uri = null, $request_data = null, array $headers = [])
    {
        // Functionality to prepare app to process request
    }
}

bootstrap 文件夹中的 dependencies.php 文件如下所示:

<?php

$config = require_once '../config/index.php';

$app = new \Slim\App(['settings' => $config]);

$dependencies = require_once 'dependencies.php';
$dependencies($app);

$routes = require_once '../routes/web.php';
$routes($app);

return $app;

每当我尝试 运行 这个:./vendor/bin/phpunit --verbose,我得到错误:

Error: Function name must be a string` on TestCase.php Line: 26

我注释掉也是一样,只留下$routes = require_once...部分; 运行测试在该行抛出相同的错误。

同样的 dependencies.php 是我用来访问邮递员应用程序上的路由的东西,一切看起来都很好,但在 运行ning 测试时却不是。

我不知道发生了什么或者我做的不对。有什么办法可以解决这个问题吗?

这是由 require_once 用法引起的

你需要意识到在测试期间,这一行 require_once 被调用不止一次(假设你有多个测试场景 createApplication() 调用,因为 phpunit setUp() 是在每次测试前调用)

require_once 被调用时 "again" 它将 return "true" 而不是从所需文件 return 编辑的任何值 ;)

看看下面的例子:

<?php // inc.php
return 'foo';

<?php // test.php
$a = require_once 'inc.php';
$b = require_once 'inc.php';
var_dump($a, $b);

调用 test.php 将产生

string(3) "foo"
bool(true)

您需要使用 require 而不是 require_once

  • 此外,如果您在文件中有一些逻辑,您可能需要修复此问题(取决于代码在所需文件中的作用)