【问题标题】:Slim Test Error: Function name must be a stringSlim 测试错误:函数名必须是字符串
【发布时间】:2019-08-17 17:12:31
【问题描述】:

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

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

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

// 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 是我用来访问我的邮递员应用程序上的路由的,一切看起来都很好,但在运行测试时却不行。

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

【问题讨论】:

  • $app = new \Slim\App(['settings' =&gt; $config]); 在 $config 为 = require_once 时没有意义你想在这里做什么?
  • @tim `require_once DIR 。 '/../config/index.php'` 返回一个数组。因此,如果您在该行之后执行var_dump($config),您将得到等同于$config = [... settings data ...]
  • 好的,只要在该文件中定义了$config 就可以了,但是该行上的`$config=` 实际上什么都不做,因为requre_once 没有返回值。查看苗条的文档,如果$config 的格式正确,您应该只使用$app = new \Slim\App($config);

标签: php slim slim-3


【解决方案1】:

这是由require_once 使用引起的

您需要意识到,在测试期间,require_once 的这一行被多次调用(假设您有多个使用createApplication() 调用的测试场景,因为在每次测试之前都会调用phpunit setUp()

当“再次”调用require_once 时,它将返回"true",而不是从所需文件返回的任何值;)

看看下面的例子:

<?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

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

【讨论】:

  • 非常感谢@jDolba,这实际上修复了错误。
猜你喜欢
  • 2012-01-03
  • 1970-01-01
  • 1970-01-01
  • 2020-05-26
  • 2011-02-27
  • 1970-01-01
  • 2012-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多