gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:42:31 25 4
gpt4 key购买 nike

我正在使用 PHPUnit 测试一个具有许多功能的类。PHPUnit 框架从上到下运行测试函数。

问题是:如何在不重新排序源代码的情况下按指定顺序运行测试函数。

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

  • 测试函数1
  • 测试函数2
  • 测试函数3
  • 测试函数4
  • 测试函数5

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

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

最佳答案

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

关于php - 如何在 PHPUnit 中以编程方式对测试函数进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5508623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com