有全局变量的替代方案吗?我不知道';我不想在phpunit测试中使用全局变量
我正在使用phpunit创建一些测试,但遇到了一个小问题。我在类外部创建了一个有全局变量的替代方案吗?我不知道';我不想在phpunit测试中使用全局变量,php,json,phpunit,scope,global,Php,Json,Phpunit,Scope,Global,我正在使用phpunit创建一些测试,但遇到了一个小问题。我在类外部创建了一个$json字符串,并在测试函数内部使用它,以避免重复的变量声明,因为将有几十个其他测试使用相同的$json字符串 现在我已经阅读了关于我们不应该使用全局变量的内容,因为它会在代码的可维护性方面造成困难,所以我试图找出运行此测试的另一种方法 我曾想过为函数创建参数以接受,但当我运行phpunit时,这些函数会自动运行 这是我的密码: $json = '{ "name": "John",
$json
字符串,并在测试函数内部使用它,以避免重复的变量声明,因为将有几十个其他测试使用相同的$json
字符串
现在我已经阅读了关于我们不应该使用全局变量的内容,因为它会在代码的可维护性方面造成困难,所以我试图找出运行此测试的另一种方法
我曾想过为函数创建参数以接受,但当我运行phpunit时,这些函数会自动运行
这是我的密码:
$json = '{
"name": "John",
"age": "22",
}';
$data= json_decode($json, true);
$name = $data['name'];
$age = $data['age'];
class UserTest extends TestCase {
public function testCreateUserName(){
global $json;
global $name;
$this->call('POST', 'user', array(), array(), array(), $json);
$this->assertFalse($this->client->getResponse()->isOk());
$decodedOutput = json_decode($this->client->getResponse()->getContent());
$this->assertEquals($name, $decodedOutput->name, 'Name Input was Incorrect');
$this->assertResponseStatus(201);
}
}
我的问题是,还有什么替代方案 为什么不在
setUp()
方法中创建数据
例如:
class UserTest extends TestCase {
private $data;
private $json;
private $name;
private $age;
public function setUp() {
$this->json = '{
"name": "John",
"age": "22",
}';
$this->data = json_decode($this->json, true);
$this->name = $this->data['name'];
$this->age = $this->data['age'];
}
public function testCreateUserName(){
$this->call('POST', 'user', array(), array(), array(), $this->json);
$this->assertFalse($this->client->getResponse()->isOk());
$decodedOutput = json_decode($this->client->getResponse()->getContent());
$this->assertEquals($this->name, $decodedOutput->name, 'Name Input was Incorrect');
$this->assertResponseStatus(201);
}
}
有关更多信息,请参阅此链接:
在执行初始化类变量的每个测试之前,应该使用PHPUnit调用的
setUp()
方法
class UserTest extends TestCase
{
protected $json;
protected $name;
protected $age;
public function setUp()
{
$this->json = '{"name":"John","age":22}';
$data = json_decode($this->json);
$this->name = $data['name'];
$this->age = $data['age'];
}
public function testCreateUserName()
{
// ...
}
}
还有一个对称的方法teardown()
,在每次测试后调用,尽管很少需要定义这个方法
有关更多信息,请查看上的PHPUnit手册页面。我建议进一步阅读手册,了解如何使测试相互依赖,或者如何让一个测试向另一个测试提供数据。出于某种奇怪的原因,当我添加
setUp()
方法时,当我测试调用('GET,'route')时,它会抛出错误代码>你的测试用例是什么样的?也许你有什么重要的事?我假设TestCase
本身继承自PHPUnit\u Framework\u TestCase
?正如我在前面的回答中所提到的,每当我编写setUp()
方法时,它都会因为某种原因使我的测试出错。我总是得到一个call\u user\u func\u array()期望参数1是一个有效的回调,第一个数组成员不是有效的类名或对象
错误,但是当我删除setUp()
方法时,一切又神奇地工作了。您是否在TestCase中编写了一些代码来调用call\u user\u func\u array()
?您的setUp()
方法是什么样的?