我正在尝试使用Codeception来运行我的Laravel 4单元测试。
为没有依赖项的简单类运行测试可以正常工作。但是当我实例化一个依赖于 Eloquent 的模型时,我得到这个致命错误:
PHP 致命错误:在第 4 行的/var/www/project/app/models/Role.php 中找不到类"雄辩"
单元测试:
<?php
use CodeceptionUtilStub;
class TestModel extends CodeceptionTestCaseTest
{
public function testExample()
{
$role = new Role;
$role->name = 'superuser';
$this->assertEquals('superuser', $role->name);
}
}
型:
<?php
class Role extends Eloquent
{
public function users()
{
return $this->belongsToMany('User');
}
}
项目结构:
我正在从项目根目录运行供应商/bin/codecept 运行单元,具有以下文件结构:
/project
codeception.yml
/vendor/bin/codecept
/app
/tests
unit.suite.yml
/unit
ExampleTest.php
/models
Role.php
...etc
我做错了什么?
通过查看Codeception L4示例应用程序,我能够了解如何通过将以下行添加到project/app/tests/_boostrap.php来引导自动加载来解决此问题:
include __DIR__.'/../../vendor/autoload.php';
$app = require_once __DIR__.'/../../bootstrap/start.php';
CodeceptionUtilAutoload::registerSuffix('Page', __DIR__.DIRECTORY_SEPARATOR.'_pages');
编辑:从Laravel4.0升级到4.1时,还需要添加额外的行:
$app->boot();
我可能迟到了,但如果你不需要代码的东西。你应该扩展laravel的实现PHPUnit_Framework_TestCase称为TestCase。喜欢这个:
class TestModel extends TestCase {
}
这个问题的答案现在有点过时了。在Laravel 5中,我得到了同样的错误(找不到类'Eloquent'...),并通过从Laravels基础TestCase.php文件中复制代码来解决它。此文件用于在Laravel框架内进行测试(不使用codeception)。
若要修复"找不到雄辩"错误,请将以下行添加到项目/测试/单元/_bootstrap.php
<?php
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make('IlluminateContractsConsoleKernel')->bootstrap();
老实说,我不确定它为什么有效,但它确实如此!如果我弄清楚原因或有人评论,我会编辑。
运行单元测试时找不到Eloquent
类。
尝试将use IlluminateDatabaseEloquentModel as Eloquent;
添加到 Role.php
。
您可以转到 TestCase 类并通过添加身份验证或一些来覆盖方法刷新应用程序(将方法添加到 TestCase):
protected function refreshApplication()
{
$this->app = $this->createApplication();
$this->client = $this->createClient();
$this->app->setRequestForConsoleEnvironment();
$this->app->boot();
// authenticate your user here, when app is ready
$user = new User(array('username' => 'John', 'password' => 'test'));
$this->be($user);
}
我通过添加以下行来解决Laravel 4和Codeception的类似问题_bootstrap.php
$app = require __DIR__.'/../../bootstrap/start.php';
$app->boot();
希望这对谷歌同胞有所帮助!