metamodels / phpunit-contao-database
MetaModels phpunit contao 数据库类
1.0.1
2016-07-20 11:18 UTC
Requires
- php: >=5.4
- contao/core: ^3.5.5
Requires (Dev)
- phpcq/all-tasks: ~1.1
This package is auto-updated.
Last update: 2024-08-27 12:39:03 UTC
README
这里您可以期待什么。
此存储库包含可以用于模拟 Contao 数据库连接的一小部分类。
为此,您需要定义查询及其结果集。
安装
将 "metamodels/phpunit-contao-database": "~1.0"
添加到您的 composer.json
文件的 require-dev
部分,然后您就设置好了。
如何使用
在您的单元测试中,您只需通过调用以下代码替换原始的 Contao 数据库类(在原始 Contao 数据库类通过自动加载加载之前!)!一个不错的选择可能是测试用例的 setUp()
方法。
class MyTest extends \PHPUnit_Framework_TestCase { /** * Register the database. * * @return void */ public function setUp() { \MetaModels\Test\Contao\Database::register(); } }
在单元测试中使用它
您应该使用依赖注入来进行单元测试,然后您可以使用类似下面的方法
$objectToTest = new ClassToTest(); $database = \MetaModels\Test\Contao\Database::getNewTestInstance(); // Inject the database into the instance. $objectToTest->setDatabase($database); $database ->getQueryCollection() ->theQuery('SELECT * FROM test WHERE id=?') ->with(1) ->result() ->addRow( array( 'id' => 1, 'tstamp' => 343094400, 'title' => 'test' ), ); // This method will call the above query internally and will receive the given result. $result = $objectToTest->testMethod(); $this->assertEquals(1, $result->getId()); $this->assertEquals(343094400, $result->getModificationTime()); $this->assertEquals('test', $result->getTitle());
如果您不幸不能使用依赖注入,因为底层代码使用了 Database::getInstance()
,您仍然有其他选择。您可以使用方法 $database = \MetaModels\Test\Contao\Database::getNewTestInstance();
,这将返回“默认”数据库实例。
然而,不推荐使用这种方法,因为实例将在所有单元测试之间共享。