Create Eloquent Mock and Set Property Value

ropupu
ropupu
Sep 5, 2018 · 1 min read

When I write test with Laravel5.6, I needed to mock Eloquent Model like below:

use App\Model\Foo;class Target
{
public function __construct(Foo $foo)
{
$this->foo = $foo;
}

public function example()
{
$foo = clone $this->foo;
$foo->bar = 'foobar';
$foo->save();
return $foo->id;
}
}

What I need is mock of Foo and make the mock return value of id, but it took a few hours to get correct method.

That method is like below:

class TargetTest extends TestCase
{
public function testExample()
{
$fooMock = $this->createMock(Foo::class);
$fooMock
->method('__get')
->with('id')
->willReturn(1)

$target = new Target($fooMock);

// assert or something...
}
}
ropupu

Written by

ropupu

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade