【发布时间】:2014-07-22 05:50:23
【问题描述】:
我正在使用 PHPUnit @ http://there4development.com/blog/2013/10/13/unit-testing-slim-framework-applications-with-phpunit/ 关注 Slim 的测试设置
一开始我的所有逻辑都在匿名函数中
$app->get('/video/', function () use ($app) {
// all code goes here
}
通过 PHPUnit 进行的测试效果很好...
public function testVideoCountInPage1() {
$this->get('/video/');
$this->assertEquals(200, $this->response->status());
$rawResponse = $this->response->body();
$jsonResponse = json_decode($rawResponse);
$this->assertSame(20, count($jsonResponse->data));
}
但现在,我将 `get('/video/') 中的核心逻辑拆分为多个函数,如下所示:
$app->get('/video/', function () use ($app) {
// some logic
$db = openDB($dbConfig);
$page = findPageParameter($app->request()->params());
// some logic
}
function openDB($dbConfig) {
// open DB here
return $db;
}
function findPageParameter($params) {
// find page here
return (int)$page;
}
调用/video 端点时我仍然得到正确的响应。但是单元测试失败了,说
.PHP Fatal error: Cannot redeclare openDB() (previously declared in /var/www/traffic/app/routes/video.php:69) in /var/www/traffic/app/routes/video.php on line 75
更新:
一旦我用require_once 替换了几个require,这个错误就得到了修复。但是现在测试中的断言失败了
1) videoTest::testVideoCountInPage1
Failed asserting that 404 matches expected 200.
当我调用相同的端点http://localhost/traffic/index.php/video 时,我会得到正确结果的状态 200。当 PHPUnit 调用同一个端点时,它返回 404
更新 2:
单元测试,我在其中测试各个函数 openDB() 和 findPageParameter() 工作正常。只有 SLIM REST API 的端端测试失败并出现 404...
参考:
- video.php (https://github.com/GethuGames/Traffic-Violation-Portal-REST-API/blob/toDB/app/routes/video.php)
- videoTest.php (https://github.com/GethuGames/Traffic-Violation-Portal-REST-API/blob/toDB/tests/integration/videoTest.php)(端到端测试失败)
- videoUnitTest.php (https://github.com/GethuGames/Traffic-Violation-Portal-REST-API/blob/toDB/tests/unit/videoUnitTest.php)(有效的单元测试)
- 整个项目@https://github.com/GethuGames/Traffic-Violation-Portal-REST-API/tree/toDB
【问题讨论】:
-
您尝试多次声明函数,例如。由于多包含文件。如果是这样,请使用
require/include_once而不是require/include。 -
你确定你的代码是这样的吗?错误消息似乎表明
openDB()函数是在同一文件 (video.php) 的第 69 行 和 75 处定义的 -
@panther 谢谢它的工作:-) @Phil 是的,我在底部链接了
video.php但是现在断言失败了..