如何在PHPUnit中以编程方式对测试函数进行排序?

时间:2011-04-01 02:43:42

标签: php unit-testing phpunit

我正在使用PHPUnit来测试具有许多功能的类。 PHPUnit框架从顶部到底部运行测试功能。

问题是:如何在指定的顺序中运行测试函数,而无需在源代码中重新排序。

为了澄清这个问题,假设我们有5个测试函数;

  • testFunc1
  • testFunc2
  • testFunc3
  • testFunc4
  • testFunc5

框架将运行testFunc1,然后运行testFunc2,直到它到达testFunc5。

但是,我想运行testFunc3然后是testFunc1然后是testFunc5然后是testFunc2然后是testFunc4而不在源文件中重新排序它们。

3 个答案:

答案 0 :(得分:4)

PHPUnit将按照*_TestCase类中编写的确切顺序执行测试。

这些测试中的每一个都应该能够独立运行,而不依赖于之前执行的其他测试。

如果您对数据库进行测试时出现问题,我建议使用类似的方法:

class MyTest extends PHPUnit_Framework_TestCase {

    public function setUp() {
        // REPLACE INTO testDb (ID, NAME, VALUE) VALUES (1001000, 'testing', 'value')
        $this->db = $db_connection;
    }

    public function tearDown() {
        // DELETE FROM testDb WHERE ID > 10010000 // or something like this
    }

    public function testSelect() {
        $this->assertSame("value", $this->db->getId(100100));
    }

    /**
     * @depends testSelect
     */
    public function testInsert() {
        $this->db->insertById(1001111, "mytest", "myvalue");
        $this->db->getId(1001111);
    }

    /**
     * @depends testSelect
     */
    public function testDelete() {
        $this->db->deleteById(1001000);
        $this->assertNull($this->db->getId(10010000);
    }

    // and so on
}

setUp()方法将在每个测试用例之前运行,并确保大多数测试用例所需的所有值都存在,tearDown()将在测试用例之后清除。

@depends注释将确保在选择测试失败时不运行插入测试。 (如果你无法加载值,那么插入新值并获取那些不能用于以太,不需要尝试它。)

For that also check the manual on test dependencies

答案 1 :(得分:3)

单元测试的重点实际上在名称本身,单元测试。它们独立运作,彼此之间没有任何依赖关系。如果您正确编写测试代码,则执行顺序无关紧要。

如果是数据库问题,请确保在每次测试之前都有一个干净的数据库。

答案 2 :(得分:1)

现在没有办法在重新排序文件中的函数时做到这一点。有一个功能请求使用@depends注释来重新排序测试,PHPUnit作者表达了这样做的愿望。您可以comment on the request点击PHPUnit's github tracker