PHPUnit 测试依赖于另一种方法的方法



这是我的数据库类,我想测试返回正确值的rowCount方法:

namespace MyProjectDatabase;
class Database {
// database connection
private $conn = NULL;
// holds query statement object
private $statement = NULL;
public function __construct(PDO $conn) {
$this->conn = $conn;
}
public function query(string $query, array $parameters=[]) : bool {
$this->statement = $this->conn->prepare($query);
return $this->statement->execute($parameters);
}
public function rowCount() : int {
return $this->statement->rowCount();
}
}

我最初编写了这个单元测试来测试rowCount方法,但正如你所看到的,我也使用查询方法来运行查询

class DatabaseTest extends PHPUnitFrameworkTestCase {
/** @test */
public function rowCountReturnsCorrectNumber() {
$pdo = new PDO('sqlite::memory:');
$db = new MyProjectDatabaseDatabase($pdo);
// we are not testing query method here but we use it to run the query
$db->query("CREATE TABLE test (id INT UNSIGNED PRIMARY KEY)");
$db->query("INSERT INTO test (id) VALUES (1),(2)");
$this->assertEquals(2,$db->rowCount());
}
}

我认为查询方法将来可能会出错,所以我为什么要依赖它。我写这个是为了避免它:

class DatabaseTest extends PHPUnitFrameworkTestCase {
/** @test */
public function rowCountReturnsCorrectNumber() {
$pdo = new PDO('sqlite::memory:');
$db = new MyProjectDatabaseDatabase($pdo);
$s = $pdo->prepare("CREATE TABLE test (id INT UNSIGNED PRIMARY KEY)");
$s->execute();
$s2 = $pdo->prepare("INSERT INTO test (id) VALUES (1),(2)");
$s2->execute();
// here I set statement (private property)
$reflection = new ReflectionClass($db);
$property = $reflection->getProperty('statement');
$property->setAccessible(true);
$property->setValue($db, $s2);
$this->assertEquals(2,$db->rowCount());
}
}

现在我的问题是:我认为这不是一个好方法,因为声明是私有财产。在第二次测试中,我只能测试rowCount方法,没有别的,但我使用了私有财产,我认为它会使将来的维护变得如此困难。 哪一个是正确的?我应该以另一种方式测试它吗?

您可以使用@depends,它允许您显式声明测试之间的依赖关系:

class DatabaseTest extends PHPUnitFrameworkTestCase
{
/**
* @test
*/
public function yourQueryTest()
{
// ...
}

/**
* @test
* @depends yourQueryTest
*/
public function rowCountReturnsCorrectNumber()
{
// ...
}
}

其中yourQueryTest是对MyProjectDatabaseDatabase#query的测试。

最新更新