我是單元測試的新手。我讀了documentation並嘗試做同樣的事情。如何使用PHPUnit和TestCaseTrait
首先,我有未來的環境:
$ php -v
PHP 7.0.15-1+deb.sury.org~trusty+1 (cli) (built: Jan 20 2017 09:16:11) (NTS)
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies with Zend OPcache v7.0.15-1+deb.sury.org~trusty+1, Copyright (c) 1999-2017, by Zend Technologies
$ cat composer.json
...
"require-dev": {
"phpunit/phpunit": "^6.0",
"phpunit/dbunit": "^3.0"
},
...
我有/ src目錄,/測試和/供應商目錄。 Composer自動加載器完美無缺。
我的PHP項目與MySQL數據庫緊密結合,我想要的只是單元測試這些功能。
$ cat tests/phpunit.xml
<phpunit>
<php>
<ini name="display_errors" value="On" />
<ini name="display_startup_errors" value="On" />
</php>
</phpunit>
而且測試:
$ cat tests/SimpleTest.php
<?php
use PHPUnit\Framework\TestCase;
use PHPUnit\DbUnit\TestCaseTrait;
require_once(__DIR__.'/../vendor/autoload.php');
class SimpleTest extends TestCase
{
// use TestCaseTrait;
protected function getConnection() {}
protected function getDataSet() {}
public function testFirstExample()
{
$this->assertEquals(1, 1);
}
public function testSecondExample()
{
$this->assertEquals(1, 0);
}
}
?>
$ phpunit --testdox --verbose --configuration=tests/phpunit.xml tests/SimpleTest.php
PHPUnit 6.0.6 by Sebastian Bergmann and contributors.
Runtime: PHP 7.0.15-1+deb.sury.org~trusty+1
Configuration: /home/ubuntu/workspace/tests/phpunit.xml
Simple
[x] First example
[ ] Second example
一切都很好,如預期,直到我取消對該行use TestCaseTrait;
工作。從這一刻起,測試不起作用。 他們甚至在測試函數中沒有執行(我通過添加下一個代碼來檢查它:fwrite(STDERR, 'Here we are!')
)。
問題:use TestCaseTrait;
聲明有什麼問題?爲什麼它打破了整個測試?我該如何解決它?
謝謝! P.S.對不起我的英語不好。
結論: 很奇怪,但問題是在setUp()
功能。你必須在測試中添加它!當我這樣做,我的測試正常工作...
不知道這是不是你的問題,但看[phpunit文檔](https://phpunit.de/manual/current/en/database.html)表明'getConnection'和'getDataSet'應該返回一些東西。在你的例子中它們是無效的。 – k0pernikus
當然我已經嘗試過了。這些函數分別返回 '$ this-> createDefaultDBConnection($ pdo,'test');' 和 'new MyApp_DbUnit_ArrayDataSet(array(...))' (如文檔中所示)。但它不會改變任何東西...... – GHopper