编程语言
首页 > 编程语言> > 如何在PHPUnit中的不同测试中共享对象

如何在PHPUnit中的不同测试中共享对象

作者:互联网

我具有以下类“ MyControllerTest”,用于测试“ MyController”.
我想在该类的不同测试中共享同一对象,即“ $algorithms”,但在尝试将变量添加到不同位置后,我不知道该怎么做:

class MyControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    // $algorithms = ...   <----- does not work
    public static function main()
    {
        $suite = new PHPUnit_Framework_TestSuite("MyControllerTest");
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    public function setUp()
    {
        $this->bootstrap = new Zend_Application(
                'testing',
                APPLICATION_PATH . '/configs/application.ini'
        );
        $configuration = Zend_Registry::get('configuration');
        // $algorithms = ...   <----- does not work
        parent::setUp();
    }

    public function tearDown()
    {

    }
    public function test1() {
        // this array shared in different tests
        $algorithms[0] = array(            

                        "class" => "Mobile",
                        "singleton" => "true",
                        "params" => array(
                                "mobile" => "true",
                                "phone" => "false"
                                )
                    );

        ...  
    } 
    public function test2() { };

}

如何共享该对象?
任何帮助,将不胜感激!

解决方法:

您在这里有几个选择

>将数据固定装置声明为setUp方法,并声明一个包含它的私有变量.因此,您可以在其他测试方法中使用它.
>在测试类中声明一个私有函数来保存数据.如果您需要数据夹具,只需调用private方法
>使用保存数据装置的方法创建实用程序类. Utility类在setUp函数中初始化.在MyControllerTest中声明一个私有变量,该私有变量保存Utility类的实例.当测试需要夹具时,只需从Utility实例调用夹具方法.

例子1

class MyControllerTest extends Zend_Test_PHPUnit_ControllerTestCase 
{
  private $alg;

  public function setUp()
  {
    # variable that holds the data fixture
    $this->alg = array(....);
  }

  public function test1()
  {
     $this->assertCount(1, $this->alg);
  }
}

例子2

class MyControllerTest extends Zend_Test_PHPUnit_ControllerTestCase 
{
  public function test1()
  {
     $this->assertCount(1, $this->getAlgo());
  }

  # Function that holds the data fixture
  private function getAlgo()
  {
    return array(....);
  }
}

例子3

class Utility
{
  # Function that holds the data fixture
  public function getAlgo()
  {
    return array(....);
  }
}

class MyControllerTest extends Zend_Test_PHPUnit_ControllerTestCase 
{
  private $utility;

  public function setUp()
  {
    $this->utility = new Utility();
  }

  public function test1()
  {
     $this->assertCount(1, $this->utility->getAlgo());
  }
}

但是要当心在某些测试中共享和更改的灯具.这确实会弄乱您的测试套件.

标签:phpunit,zend-framework,php
来源: https://codeday.me/bug/20191121/2051749.html