这是我的数据库类,我想测试返回正确值的rowCount方法:
namespace MyProject\Database;
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 \PHPUnit\Framework\TestCase {
/** @test */
public function rowCountReturnsCorrectNumber() {
$pdo = new \PDO('sqlite::memory:');
$db = new \MyProject\Database\Database($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 \PHPUnit\Framework\TestCase {
/** @test */
public function rowCountReturnsCorrectNumber() {
$pdo = new \PDO('sqlite::memory:');
$db = new \MyProject\Database\Database($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方法,除了我使用了私有财产之外,我什么都没有,我认为它会使将来的维护变得如此困难。哪一个是正确的?我应该用另一种方式测试它吗?
吃鸡游戏