用于测试用例的PHPUnit设置和tearDown

时间:2013-12-10 23:52:39

标签: unit-testing phpunit

PHPUnit在测试用例中的每个测试之前和之后分别运行setuptearDown个事件。在我的特定场景中,我还希望运行类似testCaseSetuptestCaseTearDown的内容。这可能吗?

目前的解决方案如下:

<?php

class MyTestCase extends \PHPUnit_Framework_TestCase
{

    public function __construct($name = NULL, array $data = array(), $dataName = '')
    {
        // My test case setup logic
        parent::__construct($name, $data, $dataName);
    }

    public function __destruct()
    {
        // My test case tear down logic
    }
}

但由于以下原因,它似乎远非最佳:

  • 我必须重新声明PHPUnit_Framework_TestCase构造并重定向任何参数。如果在版本更新时更改了PHPUnit构造函数,我的测试用例将停止。
  • 可能PHPUnit_Framework_TestCase未被宣布为像这样使用。

我想知道是否有更好的解决方案。有什么想法吗?

1 个答案:

答案 0 :(得分:10)

是的,为此目的有一些特殊方法:setUpBeforeClasstearDownAfterClass

class TemplateMethodsTest extends PHPUnit_Framework_TestCase
{
    public static function setUpBeforeClass()
    {
        // do sth before the first test
    } 

    public static function tearDownAfterClass()
    {
        // do sth after the last test
    }