当我的测试 class 使用它自己的构造方法时,PHPUnit 6.1.x 抛出 array_merge() 错误

PHPUnit 6.1.x throws array_merge() error when my test class uses its own constructor method

我收到这个错误:

1) XTest::testX
array_merge(): Argument #1 is not an array

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

关于这个测试用例:

use PHPUnit\Framework\TestCase;

class XTest extends TestCase
{

    function __construct()
    {}

    function testX()
    {
        $this->assertTrue(true);
    }
}

如果我删除 __construct 方法,我的测试就会通过。 PHPUnit 对我的 class 构造方法的处理发生了什么?它在 PHPUnit 版本 4.8 中运行良好,但现在我使用的是 PHPUnit 版本 6.1.3

PHPUnit使用构造函数来初始化基TestCase

你可以在这里看到构造方法: https://github.com/sebastianbergmann/phpunit/blob/6.1.3/src/Framework/TestCase.php#L328

public function __construct($name = null, array $data = [], $dataName = '')

您不应该使用构造函数,因为它由 phpunit 使用,并且对签名等的任何更改都可能破坏一切。

您可以使用 phpunit 会为您调用的特殊 setUpsetUpBeforeClass 方法。

use PHPUnit\Framework\TestCase;

class XTest extends TestCase
{
    function static setUpBeforeClass()
    { 
       // Called once just like normal constructor
       // You can create database connections here etc
    }

    function setUp()
    {
      //Initialize the test case
      //Called for every defined test
    }

    function testX()
    {
        $this->assertTrue(true);
    }

    // Clean up the test case, called for every defined test
    public function tearDown() { }

    // Clean up the whole test class
    public static function tearDownAfterClass() { }
}

文档:https://phpunit.de/manual/current/en/fixtures.html

请注意,setUp 会针对 class 中的每个指定测试调用。

对于单个初始化,您可以使用 setUpBeforeClass

另一个提示:运行 你的 phpunit 带有 -v 标志来显示堆栈跟踪 ;)

正如 Sander Visser 的回答正确指出的那样,父构造函数可能有额外的参数等,通常你会想使用 setUpBeforeClasssetUp,但是,如果你知道你的重新做,你可以在你的测试的构造函数中调用 parent::__construct(); class:

public function __construct() {
    parent::__construct();
    // Your construct here
}

编辑 2019

在 Codeception 中,这也可能是由于套件文件中的 YML 缩进无效造成的。