Laravel 和 Lumen 都有自己整理好的一套 unit test framework,因此若要加入 AspectMock 會需要對預設的 boostrap file 做一些調整。
整合時需要注意的事情:
- 需要改寫
/bootstrap/app.php phpunit.xml中的 bootstrap config,要改成自己新建立的 bootstrap file- 注意
require順序,不要讓 Laravel App 的資料被覆蓋掉 (另外也要注意require和require_once的差異)
建立新的 bootstrap 設定檔 /tests/bootstrap.php:
<?php
// composer autoload
require_once __DIR__.'/../vendor/autoload.php';
// load Laravel bootstrap
$app = require_once __DIR__ . '/../bootstrap/app.php';
// create temporary folder for AspectMock
$tmpPath = '/tmp/aspectMock/';
if (!file_exists($tmpPath)) {
mkdir($tmpPath, 0777);
}
$kernel = \AspectMock\Kernel::getInstance();
$kernel->init([
'appDir' => __DIR__ . '/..',
'debug' => true,
'includePaths' => [
__DIR__ . '/../app',
__DIR__ . '/../vendor/laravel', // 如果需要 mock Model 則加上這行
],
'excludePaths' => __DIR__, // "/tests" 目錄不需要處理
'cacheDir' => $tmpPath,
]);
return $app; // 把 App 回傳給 createApplication()
接下來要調整原有的 phpunit.xml 設定檔,需要參考 AspectMock 的要求,來調整:
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="tests/bootstrap.php"
backupGlobals="false">
注意最後面二行,bootstrap 要改成剛剛新建立的檔案,backupGlobals 則要關閉。
最後,去調整 BaseTest.php,在 tearDown() 加上 AspectMock 清理設定的指令:
protected function tearDown(): void
{
test::clean();
}
另外在 createApplication() 這邊,要改用上面建立的 bootstrap file:
public function createApplication()
{
return require __DIR__ . '/bootstrap.php';
}
以上全部改好的話,執行 vendor/bin/phpunit 應該可以正常運作。
Error: Call to a member function make() on boolean
注意 require 和 require_once 的差異,Laravel 會在每次開始 unit test 之前,重新建立 $app,所以用 require_once 的話,就的設定清不掉
-$app = require_once __DIR__ . '/../bootstrap/app.php'; // Laravel bootstrap +$app = require __DIR__ . '/../bootstrap/app.php';