Laravel 4-使用PHPUnit和mockry进行存储库模式测试
我正在为一个客户开发一个应用程序,但在测试存储库时遇到了问题 要将存储库绑定到模型,我有以下代码:Laravel 4-使用PHPUnit和mockry进行存储库模式测试,laravel,mocking,phpunit,repository-pattern,mockery,Laravel,Mocking,Phpunit,Repository Pattern,Mockery,我正在为一个客户开发一个应用程序,但在测试存储库时遇到了问题 要将存储库绑定到模型,我有以下代码: <?php namespace FD\Repo; use App; use Config; /** * Service Provider for Repository */ class RepoServiceProvider extends \Illuminate\Support\ServiceProvider { public function register()
<?php
namespace FD\Repo;
use App;
use Config;
/**
* Service Provider for Repository
*/
class RepoServiceProvider extends \Illuminate\Support\ServiceProvider
{
public function register()
{
$app = $this->app;
$app->bind('FD\Repo\FactureSst\FactureSstInterface', function ($app) {
return new FactureSst\EloquentFactureSst(App::make('FactureSst'), new \FD\Service\Cache\LaravelCache($app['cache'], 'factures_sst', 10));
});
}
}
如果我没有弄错这一行的话
$result = $this->repo->findWithSstAndBdc(30207, 10);
实际上应该是
$result = $this->mock->findWithSstAndBdc(30207, 10);
还请记住,您可以模拟整个调用链(对于这样流畅的查询非常有用):
我还将使用PHP的内置foreach()而不是使用$factures->each,因为这样就少了一件要测试的东西。看起来就像是在模拟存储库本身,而实际上是在模拟该存储库的依赖关系,即illumb\Database\elount\Model
,这就是您要访问数据库的地方
更改setUp()
,以便它创建illighted\Database\elount\Model
的模拟对象,然后在实例化存储库时让它注入该模拟对象
public function setUp()
{
parent::setUp();
$this->mock = m::mock('Illuminate\Database\Eloquent\Model'); // Or better if you mock 'FactureSst'
$this->app->instance('FactureSst', $this->mock);
}
这有点令人困惑,因为您声明抽象类包含ORM方法,但当您调用这些方法时,您是在注入的模型依赖项上调用它们,而不是在抽象类上调用它们。这可能就是困惑所在
此外,如果您的模型扩展了illumb\Database\elount\Model
,通常最好只将您的模型注入存储库,而不是illumb\Database\elount\Model
。这样,您还可以利用存储库中模型中设置的任何关系函数。您好,谢谢您的回复。正如建议的那样,我已经尝试用$this->mock替换$this->repo,但是现在我得到了以下错误:BadMethodCallException:MethodMockery\u 0\u FD\u repo\u FactureSst\u FactureSstInterface::FindWithssStandBDC()在此模拟对象上不存在。您好,谢谢您的回复。正如您所说的,我有一个包含ORM方法的抽象类,因此我应该调用我将不得不更改的模型。星期二我回去工作的时候我会检查它的,谢谢你的回复刚才检查了它,通过调用抽象的repo方法而不是模型,测试正在工作。谢谢
$result = $this->mock->findWithSstAndBdc(30207, 10);
$this->mock->shouldReceive('where->whereHas->get')
->once()->andReturn(/*MAKE A FAKE OBJECT HERE*/);
public function setUp()
{
parent::setUp();
$this->mock = m::mock('Illuminate\Database\Eloquent\Model'); // Or better if you mock 'FactureSst'
$this->app->instance('FactureSst', $this->mock);
}