Unit testing: mocking Model::create()

Published 4 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.