【问题标题】:Implement a constructor / destructor like functionality for methods为方法实现类似构造函数/析构函数的功能
【发布时间】:2013-11-18 09:36:28
【问题描述】:

我正在构建一个简单的(单元)测试框架,用户可以在其中测试特定的功能。

但现在我需要拥有SetUp()TearDown() 功能。我只是不确定如何实现。

我的代码如下所示:

class TestCase
{
    public function SetUp ( ) { }
    public function TearDown ( ) { }

    // Down here are alot of assertion methods
    public function AssertTrue ( )
    {
        return $this;
    }

    public function AssertFalse( )
    {
        return $this;
    }
}

另一个类然后扩展这个类:

class SomeTestCase extends TestCase
{
    public function SetUp ( )
    {
        echo 'SetUp';
    }

    public function TearDown ( )
    {
        echo 'SetUp';
    }

    public function TestMethod1 ( )
    {
        // do some test
    }

    public function TestMethod2 ( )
    {
        // do some other test
    }
}

现在SetUp() 方法需要在每个测试方法开始时运行。所以在这种情况下TestMethod1TestMethod2

TearDown() 方法需要在每个测试方法结束时运行。

但是我如何从TestCase 类中做到这一点。我不希望用户需要在每个方法中手动添加$this->SetUp()$this->TearDown()

我希望它的行为类似于__construct__destruct,但是对于每种方法。

我该怎么做?

【问题讨论】:

标签: php unit-testing


【解决方案1】:

为此,您需要将setup() 硬编码到所有方法中,这很愚蠢,或者有一个不是测试方法之一的入口点。因此,立即想到的是有一个触发器方法,它接受您或您的用户希望执行的类的名称作为参数。例如:

public function trigger($method){
    $this->SetUp();
    $this->$method;
}

你从魔术函数__call得到方法名

public function __call($method){
    $this->trigger($method);
}

正如您可能已经想到的那样,您不能拥有与其“调用”名称相同名称的类,因为这样__call 将永远不会执行。您需要在要调用的方法名称和没有人知道的虚拟名称之间建立关系。

private $methodRelations = array(
    'testMethod1' => 'dummyMethod1',
    'testMethod2' => 'dummyMethod2'
)

那么整个班级会是这样的

class TestCase{
    private $methodRelations = array(
        'testMethod1' => 'dummyMethod1',
        'testMethod2' => 'dummyMethod2'
    )

    public function __call($method){
        $this->trigger($this->methodRelations[$method]);
    }

    public function trigger($method){
        $this->SetUp();
        $this->$method;
    }

    public function dummyMethod1( )
    {
        // do some test
    }

    public function dummyMethod2( )
    {
        // do some test
    }
}

为了更整洁的外观,您可以将trigger__call 结合使用,但为了更好地理解,我将它们分开了。祝你好运!

【讨论】:

  • TestCase 类也包含断言?我需要抽象。我不认为这对我有用
猜你喜欢
  • 2014-05-27
  • 2015-06-30
  • 1970-01-01
  • 2012-12-24
  • 2011-04-06
  • 2011-06-29
  • 2013-07-07
  • 2020-08-01
  • 2019-07-31
相关资源
最近更新 更多