Create Eloquent Mock and Set Property Value
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...
}
}