如何模拟一个雄辩模型的静态方法? [英] How to mock static methods of an Eloquent model?

查看:126
本文介绍了如何模拟一个雄辩模型的静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的代码中有这样的一行:

  ModelName :: create($ data); 

其中ModelName只是一个 Eloquent 模型。在单元测试中有没有办法模拟这个电话?我试过:

  $ client_mock = \Mockery :: mock('Eloquent','App \Models\ModelName ); 
$ client_mock-> shouldReceive('create')
- > with($ data) - > andReturns($ returnValue);

但它不起作用。

解决方案

你应该这样做:

  $ client_mock = \Mockery ::模拟( '过载:App\Models\ModelName'); 
$ client_mock-> shouldReceive('create') - > with($ data) - > andReturn($ returnValue);

我们使用 overload:因为你不想通过模拟某些类,但是您也想使用它,以防它被硬编码到某些类中。



除了您的测试类(就在 class 之前),您应该添加:

  / ** 
* @runTestsInSeparateProcesses
* @preserveGlobalState已禁用
* /

以避免这个类已经加载的错误(它可能没有它在单个测试中工作,但是当你运行多个测试可能不会)



您可能会阅读详细了解



更新



在某些情况下,可能无法使用此方法来模拟类。在这种情况下,您可以创建正常的模拟(没有 orverload ),并将其注入服务容器,如下所示:

 应用::实例( '\App\Models\ModelName',$ client_mock); 


I have in my code a line like this:

ModelName::create($data);

where ModelName is just an Eloquent model. Is there a way to mock this call inside a unit test? I tried with:

$client_mock = \Mockery::mock('Eloquent','App\Models\ModelName');
$client_mock->shouldReceive('create')
            ->with($data)->andReturns($returnValue);

but it doesn't work.

解决方案

You should do something like this:

$client_mock = \Mockery::mock('overload:App\Models\ModelName');
$client_mock->shouldReceive('create')->with($data)->andReturn($returnValue);

We are using overload: because you don't want to pass mock to some class, but you want to use it also in case it's hard-coded into some classes.

In addition to your test class (just before class) you should add:

/**
 * @runTestsInSeparateProcesses
 * @preserveGlobalState disabled
 */

to avoid errors that this class was already loaded (it might work without it in single test but when you are running multiple tests probably it won't).

You might read Mocking hard dependencies for details about it.

UPDATE

In some cases it might be not possible to mock class using this method. In those cases you can create normal mock (without orverload) and inject it to service container like so:

App::instance('\App\Models\ModelName',$client_mock); 

这篇关于如何模拟一个雄辩模型的静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆