phpunit 的代码覆盖率;无法到达一个地方
在 xdebug 代码覆盖率中,它显示了“return false;”行(在“!$r”下方)我的测试未涵盖。但是,$sql 基本上是硬编码的。我如何获得相关报道?我是否以某种方式覆盖“$table”?或者为了这部分测试而关闭数据库服务器?
我想这可能告诉我我的模型写得不好,对吧?因为我无法很好地测试它。我怎样才能写得更好?
由于这一行没有被覆盖,整个方法也没有被覆盖,报告也被关闭。
我对 phpunit 还很陌生。谢谢。
public function retrieve_all()
{
$table = $this->tablename();
$sql = "SELECT t.* FROM `{$table}` as t";
$r = dbq ( $sql, 'read' );
if(!$r)
{
return false;
}
$ret = array ();
while ( $rs = mysql_fetch_array ( $r, MYSQL_ASSOC ) )
{
$ret[] = $rs;
}
return $ret;
}
In the xdebug code coverage, it shows the line "return false;" (below "!$r") as not covered by my tests. But, the $sql is basically hard-coded. How do I get coverage on that? Do I overwrite "$table" somehow? Or kill the database server for this part of the test?
I guess this is probably telling me I'm not writing my model very well, right? Because I can't test it well. How can I write this better?
Since this one line is not covered, the whole method is not covered and the reports are off.
I'm fairly new to phpunit. Thanks.
public function retrieve_all()
{
$table = $this->tablename();
$sql = "SELECT t.* FROM `{$table}` as t";
$r = dbq ( $sql, 'read' );
if(!$r)
{
return false;
}
$ret = array ();
while ( $rs = mysql_fetch_array ( $r, MYSQL_ASSOC ) )
{
$ret[] = $rs;
}
return $ret;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我猜函数
dbq()
执行数据库查询。只需拔掉数据库连接并重新运行测试即可。测试遇到问题的原因是您正在使用全局资源:数据库连接。通常,您可以通过向测试方法(或类)提供连接对象来避免此问题。
I guess the function
dbq()
performs a database query. Just unplug your database connection and re-run the test.The reason you have trouble testing is that you are using a global resource: your database connection. You would normally avoid this problem by providing your connection object to the test method (or class).
理论上,您应该更好地将模型和所有数据库相关代码分开。
例如,在 Zend Framework 中,快速入门指南建议您:
这是一个非常有趣的模型,您应该看一下它,它使您能够真正将模型与数据分开,从而仅对模型部分(并且不关心任何数据库问题/问题)
但是在您的代码中,我建议您执行一个测试,其中 dbq() 函数返回 false (也许数据库连接是不可能“故意”),以获得完整的代码覆盖率。
我经常遇到这种情况,测试所有“错误情况”会花费太多时间,所以我放弃了 100% 代码覆盖率。
In theory, you should be better separating the model and all the database related code.
In exemple, in Zend Framework, the quickstart guide advise you to have :
This is a really interesting model, you should have a look at it, it enables you to really separate the model from the data, and thus to perform tests only onto the model part (and don't care about any database problem/question)
But in your code, I suggest you to perform a test where you have the dbq() function to return false (maybe having the db connexion to be impossible "on purpose"), in order to have full code coverage.
I often have these kind of situations, where testing all the "error cases" takes you too much time, so I give up having 100% code coverage.