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

Den*_*nis 24 php phpunit constructor extends

我收到此错误:

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

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.
Run Code Online (Sandbox Code Playgroud)

在这个测试案例中:

use PHPUnit\Framework\TestCase;

class XTest extends TestCase
{

    function __construct()
    {}

    function testX()
    {
        $this->assertTrue(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

San*_*ser 40

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

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

public function __construct($name = null, array $data = [], $dataName = '')
Run Code Online (Sandbox Code Playgroud)

你不应该使用构造函数,因为它被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() { }
}
Run Code Online (Sandbox Code Playgroud)

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

请注意,setUp为类中的每个指定测试调用gets.

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

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

  • @SebastianBergmann我觉得这很合乎逻辑.但是因为它确实在PHPUnit 4.8中工作,所以看到比``array_merge()更具描述性的错误信息会非常好:参数#1不是数组``.也许应该使用类似``setUp()的提示而不是__construct()``. (3认同)
  • 不,使用构造函数不是解决方案.使用`setUp()`. (2认同)

Luc*_*nte 10

你可以调用parent::__construct();你的Test类:

public function __construct() {
    parent::__construct();
    // Your construct here
}
Run Code Online (Sandbox Code Playgroud)