在Laravel测试单元中的__ -Construct无法填充属性
我创建了一个这样的简单测试:
namespace Tests\Feature;
use Tests\TestCase;
use App\Models\User;
use Illuminate\Support\Facades\Config;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
class simpleTest extends TestCase
{
public $form_array = ['forms_data'];
/**
* A basic feature test example.
*
* @return void
*/
public function test_example()
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
上面的测试没有问题。
我有一个公共属性$ form_array,在上面的示例中具有静态值,但是当我尝试用 __ construct()
填充$ form_array时,我会得到此错误:
array_merge(): Argument #1 must be of type array, null given
at vendor/phpunit/phpunit/phpunit:98
94▕ unset($options);
95▕
96▕ require PHPUNIT_COMPOSER_INSTALL;
97▕
➜ 98▕ PHPUnit\TextUI\Command::main();
99▕
代码:
namespace Tests\Feature;
use Tests\TestCase;
use App\Models\User;
use Illuminate\Support\Facades\Config;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
class simpleTest extends TestCase
{
public $form_array;
public function __construct(){
$this->form_array = ['forms_data'];
}
/**
* A basic feature test example.
*
* @return void
*/
public function test_example()
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
我的目标是在laravel中使用配置文件中的值填充$ form_data,我找到了这种方式:
public function __construct(){
parent::setUp();
$this->form_array = Config::get('ravandro.form_array');
}
但是,即使是简单的 $ this-form_data ='value'
不起作用,我真的很困惑!
顺便说一句,我使用Laravel Octane为我的应用服务,但我认为这对测试没有任何影响。
PHP版本:8.1
Laravel:9
php-unit:“ phpunit/phpunit”:“^9.3.3”
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在测试中,正确的构造方法被称为
setup()
,该方法在该类上的每个测试之前运行。您可以在
In tests the correct constructor method is called
setUp()
, which runs before every test on that class.You can check an example of this on https://phpunit.readthedocs.io/en/9.5/fixtures.html#fixtures