全局变量有什么替代方案吗?我不想在phpunit测试中使用全局变量



我正在使用phpunit创建一些测试,我遇到了一个小问题。我在类之外创建了一个$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);

}
}

我的问题是,还有什么替代方案?

您应该在执行每个测试之前使用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手册中的fixture页以获取更多信息。我建议进一步查看手册,了解如何使测试相互依赖或让一个测试向另一个测试提供数据。

为什么不在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);
  }  
}

查看此链接获取更多信息:

http://phpunit.de/manual/4.1/en/fixtures.html

最新更新