Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

unit testing - How to mock static methods of a Laravel Eloquent model?

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','AppModelsModelName');
$client_mock->shouldReceive('create')
            ->with($data)->andReturns($returnValue);

but it doesn't work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should do something like this:

$client_mock = Mockery::mock('overload:AppModelsModelName');
$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 classes using this method. In those cases you can create a normal mock (without overload) and inject it to the service container like so:

App::instance('AppModelsModelName', $client_mock); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...