Запустите приложение Laravel Asgard CMS со многими установленными основными модулями и несколькими внутренними модулями. Был написан модульный тест для этих модулей, но возникли проблемы с тестированием конечных точек модулей, как внешних, так и внутренних маршрутов. Я использую Phpunit с Sqlite в тестировании памяти. Как правильно сделать это?
Запуск в Windows, PHP 7.3, Laravel 5.5, PhpUnit 6, Asgardcms 3
Вот как я расширяю Orchestra Testcase:
namespace Modules\Region\Tests;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Eloquent\Model;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider;
use Modules\Region\Providers\RegionServiceProvider;
use Modules\Region\Providers\RouteServiceProvider;
use Modules\Region\Repositories\RegionRepository;
use Faker\Factory;
use Illuminate\Support\Str;
use Orchestra\Testbench\TestCase;
abstract class BaseRegionTest extends TestCase
{
/**
* @var RegionRepository
*/
protected $region;
public function setUp() {
parent::setUp();
$this->resetDatabase();
$this->region = app(RegionRepository::class);
}
protected function getPackageProviders($app) {
return [
LaravelLocalizationServiceProvider::class,
RegionServiceProvider::class,
RouteServiceProvider::class,
];
}
protected function getPackageAliases($app)
{
return [
'Eloquent' => Model::class,
'LaravelLocalization' => LaravelLocalization::class,
];
}
protected function getEnvironmentSetUp($app) {
$app['path.base'] = __DIR__ . '/..';
$app['config']->set('modules.namespace', 'Modules/Region');
$app['config']->set('translatable.locales', ['en', 'fr']);
$app['config']->set('laravellocalization.supportedLocales', [
'en' => [
'name' => 'English',
'script' => 'Latn',
'native' => 'English',
'regional' => 'en_GB',
],
'fr' => [
'name' => 'Français',
'script' => 'Latn',
'native' => 'Français',
'regional' => 'fr_FR',
],
]);
}
private function resetDatabase() {
// Relative to the testbench app folder: vendors/orchestra/testbench/src/fixture
$migrationsPath = 'Database/Migrations';
$artisan = $this->app->make(Kernel::class);
// Makes sure the migrations table is created
$artisan->call('migrate', [
'--database' => 'sqlite',
]);
// We empty all tables
$artisan->call('migrate:reset', [
'--database' => 'sqlite',
]);
// Migrate
$artisan->call('migrate', [
'--database' => 'sqlite',
]);
$artisan->call('migrate', [
'--database' => 'sqlite',
'--path' => 'Modules/Region/Database/Migrations',
]);
}
public function createRegion($args = [])
{
$faker = Factory::create();
$name = $args['name'] ?? $faker->title;
$slug = Str::slug($name);
$locales = \LaravelLocalization::getSupportedLocales();
$data = [
'locations' => [],
];
foreach ($locales as $locale => $value) {
$data[$locale] = [
'copy' => $faker->paragraph,
'name' => $name,
'slug' => $args['slug'] ?? $slug,
];
}
return $this->region->create($data);
}
}
Мой тест:
namespace Modules\Region\Tests;
use Illuminate\Foundation\Testing\WithoutMiddleware;
require("Modules\Core\helpers.php");
class EloquentRegionRepositoryTest extends BaseRegionTest
{
use WithoutMiddleware;
/** @test */
public function it_can_create_a_region()
{
$this->get('region\regions')->assertStatus(200);
}
Мои маршруты (в данном случае только бэкенд):
$router->group(['prefix' =>'/region'], function (Router $router) {
$router->bind('region', function ($id) {
return app('Modules\Region\Repositories\RegionRepository')->find($id);
});
$router->get('regions', [
'as' => 'admin.region.region.index',
'uses' => 'RegionController@index',
'middleware' => 'can:region.regions.index'
]);
$router->get('regions/create', [
'as' => 'admin.region.region.create',
'uses' => 'RegionController@create',
'middleware' => 'can:region.regions.create'
]);
$router->post('regions', [
'as' => 'admin.region.region.store',
'uses' => 'RegionController@store',
'middleware' => 'can:region.regions.create'
]);
$router->get('regions/{region}/edit', [
'as' => 'admin.region.region.edit',
'uses' => 'RegionController@edit',
'middleware' => 'can:region.regions.edit'
]);
$router->put('regions/{region}', [
'as' => 'admin.region.region.update',
'uses' => 'RegionController@update',
'middleware' => 'can:region.regions.edit'
]);
$router->delete('regions/{region}', [
'as' => 'admin.region.region.destroy',
'uses' => 'RegionController@destroy',
'middleware' => 'can:region.regions.destroy'
]);
// append
Мой файл phpunit.xml:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
verbose="true">
<testsuites>
<testsuite name="Application Test Suite">
<!-- <testsuite name="Test Suite">-->
<!-- <directory>./tests</directory>-->
<!-- </testsuite>-->
<testsuite name="Modules Test Suite">
<directory>./Modules/*/Tests</directory>
</testsuite>
</testsuite>
</testsuites>
<!-- UN-COMMENT & RUN TO GET CODE COVERAGE-->
<!-- <logging>-->
<!-- <log type="coverage-html" target="./coverage" charset="UTF-8"-->
<!-- yui="true" highlight="true" lowUpperBound="50" highLowerBound="80"-->
<!-- showUncoveredFiles="false" />-->
<!-- </logging>-->
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./Modules/*/Tests</directory>
</whitelist>
</filter>
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_URL" value="http://webdev.local"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
</php>
</phpunit>
Этовывод:
Expected status code 200 but received 404.
Failed asserting that false is true.
C:\Prototypes\webdev\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestResponse.php:78
C:\Prototypes\webdev\Modules\Region\Tests\EloquentRegionRepositoryTest.php:16
Использование ($ this-> withoutExceptionHandling):
Symfony\Component\HttpKernel\Exception\NotFoundHttpException : GET http://webdev.local/region\regions
C:\Prototypes\webdev\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\InteractsWithExceptionHandling.php:107
C:\Prototypes\webdev\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:326
C:\Prototypes\webdev\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:120
C:\Prototypes\webdev\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\MakesHttpRequests.php:345
C:\Prototypes\webdev\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\MakesHttpRequests.php:168
C:\Prototypes\webdev\Modules\Region\Tests\EloquentRegionRepositoryTest.php:17
Я уверен, что мне что-то не хватает в настройке самого теста (BaseRegionTest), ноеще не понял.
Любая помощь будет принята с благодарностью.