Unit testing: mocking Model::create()

Posted 7 months ago by CyclopsSummer

I'm writing a method (in a model) that I'm also writing unit tests for. The method calls another model's create() method. In my unit test I want to mock the Model::create() call to avoid side effects in the database, since in this instance, the unit tests are largely for speed.

How can I inject or otherwise control the model dependency? Are models a good use case for a real-time facade?

Another thought is to make a Repository to decouple the model, and mock that via a ServiceProvider, but it seems like a lot of layers for something so simple.

Here's the example:

class User extends Model {
    public function createSandwich(){
        Sandwich::create(['toppings' => ['turkey', 'lettuce', 'tomato']]);

Objective: unit test User::createSandwich() mocking Sandwich to make sure its create method is called.

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up


Reply to

Use Markdown with GitHub-flavored code blocks.